GROUPING SETS
允许你为多个列组合生成分组汇总。它类似于多个 GROUP BY
子句的 UNION ALL
操作,但更加简洁和高效
首先:创建表及接入测试数据
create table students
(id number(15,0),
area varchar2(10),
stu_type varchar2(2),
score number(20,2));
insert into students values(1, '111', 'g', 80 );
insert into students values(1, '111', 'j', 80 );
insert into students values(1, '222', 'g', 89 );
insert into students values(1, '222', 'g', 68 );
insert into students values(2, '111', 'g', 80 );
insert into students values(2, '111', 'j', 70 );
insert into students values(2, '222', 'g', 60 );
insert into students values(2, '222', 'j', 65 );
insert into students values(3, '111', 'g', 75 );
insert into students values(3, '111', 'j', 58 );
insert into students values(3, '222', 'g', 58 );
insert into students values(3, '222', 'j', 90 );
insert into students values(4, '111', 'g', 89 );
insert into students values(4, '111', 'j', 90 );
insert into students values(4, '222', 'g', 90 );
insert into students values(4, '222', 'j', 89 );
commit;
sql示例:
select id, area, stu_type, sum(score) score
from students
group by grouping sets((id, area, stu_type), (id, area), id)
order by id, area, stu_type;
(id, area, stu_type)
:按照id
、area
和stu_type
三个字段进行分组,求出每个分组的score
总和。(id, area)
:按照id
和area
两个字段进行分组,求出每个分组的score
总和。id
:仅按照id
字段进行分组,求出每个分组的score
总和。
GROUPING SETS
等效于 UNION ALL
的写法
select * from (select id, area, stu_type, sum(score) from students group by id, area, stu_typeunion allselect id, area, null, sum(score) from students group by id, areaunion allselect id, null, null, sum(score) from students group by id
) order by id, area, stu_type;
总结:
GROUPING SETS
是一种非常强大的 SQL 分组和聚合工具,它让我们能够在同一个查询中对多种不同的列组合进行聚合,避免了重复编写多个GROUP BY
子句的麻烦,并且比使用UNION ALL
更加高效。理解GROUPING SETS
可以帮助我们在分析数据时获得更多层次的汇总信息。-
GROUPING SETS
:提供了最大的灵活性,允许你指定任意的列组合进行分组汇总。你可以精确地控制哪些列组合需要进行聚合,而不像ROLLUP
或CUBE
那样会自动生成所有的汇总维度。