1.group by rollup(a,b,c) --group by (a,b,c), group by (a,b), group by (a), group by () 的集合
2.group by cube(a,b,c) --group by (a,b,c),
group by (a,b), group by (a,c), group by (b,c),
group by (a), group by (b), group by(c)
group by () 的集合
3.group by grouping sets(a,b,c) --group by (a), group by (b), group by (c) 的集合
其中,group by ()为对全表做汇总操作。
4.grouping() --GROUPING 表示GROUP BY 列表中的表达式是否参与分组,返回1 表示不参与分组,返回0 表示参与分组 。对普通GROUP BY表达式 ,GROUPING 返回0。
ROLLUP在数据统计和报表生成过程中带来极大的便利,而且效率比起来Group By + Union组合方法效率高得多。这也体现了Oracle在SQL统计分析上人性化、自动化、高效率的特点。
CUBE是ROLLUP的union集合数据。
--创建测试表group_test
create table group_test (group_id int, job varchar2(10), name varchar2(10), salary int);
--初始化数据
insert into group_test values (10,'Coding', 'Bruce',1000);
insert into group_test values (10,'Programmer','Clair',1000);
insert into group_test values (10,'Architect', 'Gideon',1000);
insert into group_test values (10,'Director', 'Hill',1000);
insert into group_test values (20,'Coding', 'Jason',2000);
insert into group_test values (20,'Programmer','Joey',2000);
insert into group_test values (20,'Architect', 'Martin',2000);
insert into group_test values (20,'Director', 'Michael',2000);
insert into group_test values (30,'Coding', 'Rebecca',3000);
insert into group_test values (30,'Programmer','Rex',3000);
insert into group_test values (30,'Architect', 'Richard',3000);
insert into group_test values (30,'Director', 'Sabrina',3000);
insert into group_test values (40,'Coding', 'Samuel',4000);
insert into group_test values (40,'Programmer','Susy',4000);
insert into group_test values (40,'Architect', 'Tina',4000);
insert into group_test values (40,'Director', 'Wendy',4000);
commit;
--ROLLUP()和CUBE()汇总一列时结果相同,如下:
select group_id,sum(salary) sums from group_test
group by rollup(group_id)
select group_id,sum(salary) sums from group_test
group by cube(group_id)
/*
ROLLUP()和CUBE()汇总多列时,ROLLUP()因字段顺序不同,结果不同。CUBE()于顺序无关。CUBE()是ROLLUP()对多个
字段每种情况排序的集合UNION。grouping()字段:如果显示“1”表示GROUPING函数对应的列(例如JOB字段)是由于ROLLUP函数所产生的空值对应的信息,即对此列进行汇总计算后的结果。 如果显示“0”表示此行对应的这列参未与ROLLUP函数分组汇总活动。
*/
select group_id,job,sum(salary) sums from group_test
group by rollup(group_id,job)
select group_id,job,sum(salary) sums from group_test
group by cube(job,group_id)
select group_id,job,sum(salary) sums from group_test
group by cube(group_id,job)
select group_id,job,grouping(GROUP_ID),grouping(JOB),sum(salary) from group_test group by rollup(group_id, job);
select
nvl(job,'-1'),
nvl(deptno,'-1'),
sum(sal) ssal from emp
group by grouping sets(job,deptno);
select
nvl(job,'-1'),
nvl(deptno,'-1'),
sum(sal) ssal,
grouping(job),
grouping(deptno) from emp
group by grouping sets(job,deptno);