postgresql分组查询
时间: 2024-04-12 17:23:59 浏览: 97
postgresql分组查询一种在数据库中根据指定的对数据进行分组的操作。通过分组查询,可以对数据进行聚合计算,例如求和、平均值、最大值、最小值等。下面是一个示例:
```
SELECT column1, aggregate_function(column2)
FROM table
GROUP BY column1;
```
其中,`column1`是要进行分组的列,`aggregate_function`是要对分组后的数据进行算的聚合函数,`table`是要查询的表名。
范例:<<引用:postgres=# select department, count(*) from employees group by department;[^1]。引用:postgres=# select department, sum(salary) from employees group by department;。引用:postgres=# select department, avg(salary) from employees group by department;[^3]。
例如,假设有一个名为`employees`的表,包含以下列:`id`、`name`、`department`和`salary`。我们可以使用分组查询来计算每个部门的员工数量、总薪资和平均薪资:
1. 计算每个部门的员工数量:
```sql
SELECT department, count(*)
FROM employees
GROUP BY department;
```
2. 计算每个部门的总薪资:
```sql
SELECT department, sum(salary)
FROM employees
GROUP BY department;
```
3. 计算每个部门的平均薪资[^3]:
```sql
SELECT department, avg(salary)
FROM employees
GROUP BY department;
```
阅读全文