说明
postgresql从9.5版本开始新加入了group by的分组集合功能,提供了GROUPING SETS,CUBE,ROLLUP参数,使用方式与oracle完全一致,下面是实际测试说明
一、创建表t并插入测试数据:
create table tmp.t(id int,name varchar(20),class int,score int);
insert into tmp.t values(1,'math',1,90);
insert into tmp.t values(2,'math',2,80);
insert into tmp.t values(3,'math',1,70);
insert into tmp.t values(4,'chinese',2,60);
insert into tmp.t values(5,'chinese',1,50);
insert into tmp.t values(6,'chinese',2,60);
insert into tmp.t values(7,'physical',1,70);
insert into tmp.t values(8,'physical',2,80);
insert into tmp.t values(9,'physical',1,90);
结果:
1.1 普通的group by
根据name和class字段求和:
select
name
,class
,sum(score)
from tmp.t
group by name,class
order by name,class
;
1.2 grouping set
GROUPING SETS的每个子列表可以指定零个或多个列或表达式,并且与其直接在GROUP BY子句中的解释方式相同。 一个空的分组集合意味着所有的行都被聚合到一个组中(即使没有输入行存在,也是输出)。
- 1
select
name
,class
,sum(score)
from tmp.t
group by grouping sets((name),(class))
order by name,class
;
- 2
select
name
,class
,sum(score)
from tmp.t
group by grouping sets((name),(class),() )
order by name,class
;
- 3
select
name
,class
,sum(score)
from tmp.t
group by grouping sets((name,class) )
order by name,class
;
等价于:
select
name
,class
,sum(score)
from tmp.t
group by name,class
order by name,class
;
- 4
select
name
,class
,sum(score)
from tmp.t
group by grouping sets((name,class),() )
order by name,class
;