扫码一下
查看教程更方便
在 postgresql 中,group by 语句和 select 语句一起使用,用来对相同的数据进行分组。这样做是为了消除适用于这些组的输出和/或计算聚合中的冗余。
group by 在一个 select 语句中,放在 whrer 子句的后面,order by 子句的前面。
下面给出了 group by 子句的基本语法:
select column-list
from table_name
where [ conditions ]
group by column1, column2....columnn
order by column1, column2....columnn
group by 子句必须放在 where 子句中的条件之后,必须放在 order by 子句之前。
在 group by 子句中,你可以对一列或者多列进行分组,但是被分组的列必须存在于列清单中。
创建 company 表( ),数据内容如下:
jiyik_db=# select * from company;
id | name | age | address | salary
---- ------- ----- ----------- --------
1 | paul | 32 | california| 20000
2 | allen | 25 | texas | 15000
3 | teddy | 23 | norway | 20000
4 | mark | 25 | rich-mond | 65000
5 | david | 27 | texas | 85000
6 | kim | 22 | south-hall| 45000
7 | james | 24 | houston | 10000
(7 rows)
下面示例将根据 name 字段值进行分组,找出每个人的工资总额:
jiyik_db=# select name, sum(salary) from company group by name;
结果如下:
name | sum
------- -------
teddy | 20000
paul | 20000
mark | 65000
david | 85000
allen | 15000
kim | 45000
james | 10000
(7 rows)
现在我们添加使用下面语句在 campany 表中添加三条记录:
insert into company values (8, 'paul', 24, 'houston', 20000.00);
insert into company values (9, 'james', 44, 'norway', 5000.00);
insert into company values (10, 'james', 45, 'texas', 5000.00);
现在 company 表中存在重复的名称,数据如下:
id | name | age | address | salary
---- ------- ----- -------------- --------
1 | paul | 32 | california | 20000
2 | allen | 25 | texas | 15000
3 | teddy | 23 | norway | 20000
4 | mark | 25 | rich-mond | 65000
5 | david | 27 | texas | 85000
6 | kim | 22 | south-hall | 45000
7 | james | 24 | houston | 10000
8 | paul | 24 | houston | 20000
9 | james | 44 | norway | 5000
10 | james | 45 | texas | 5000
(10 rows)
现在再根据 name 字段值进行分组,找出每个客户的工资总额:
jiyik_db=# select name, sum(salary) from company group by name order by name;
这时的得到的结果如下:
name | sum
------- -------
allen | 15000
david | 85000
james | 20000
kim | 45000
mark | 65000
paul | 40000
teddy | 20000
(7 rows)
下面示例将 order by 子句与 group by 子句一起使用:
jiyik_db=# select name, sum(salary) from company group by name order by name desc;
得到以下结果:
name | sum
------- -------
teddy | 20000
paul | 40000
mark | 65000
kim | 45000
james | 20000
david | 85000
allen | 15000
(7 rows)