Oracle高级查询之GROUP BY

数据库技术学习 https://www.itkc8.com

现在客户的需求是统计部门中每种工作的工资总额,最后还需要统计所有人的工资总数,相信这样的需求对大家来说还是比较简单的,很快就能写出SQL语句,如下:

select deptno, job, sum(sal) from scott.emp group by deptno, job order by deptno
	union all
select deptno, job, sum(sal) from scott.emp;

再统计每个部门的工资数吧。tnnd,我加一个union all搞定,修改后的SQL语句如下:

select deptno, job, sum(sal) from scott.emp group by deptno, job
	union all
select deptno, null job, sum(sal) from scott.emp group by deptno
	union all
select null deptno, null job, sum(sal) from scott.emp;

为什么要写的这么啰嗦呢?其实有更简介的语句可以实现同样的功能,看好了:

select deptno, job, sum(sal) from scott.emp group by rollup(deptno, job);

再统计每个工作类型的工资总额吧。tnnd,我再加一个union all再搞定,修改后的SQL语句如下:

select deptno, job, sum(sal) from scott.emp group by deptno, job
	union all
select deptno, null job, sum(sal) from scott.emp group by deptno
	union all
select null deptno, job, sum(sal) from scott.emp group by job
	union all
select null deptno, null job, sum(sal) from scott.emp;

一个简洁的SQL语句,请看

select grouping(job),deptno, job, sum(sal) from scott.emp group by cube(deptno, job)order by deptno;


只要统计部门工资总额和工作类型工资总额就可以了

select null deptno, job, sum(sal) from scott.emp group by job
	union all
select deptno, null job, sum(sal) from scott.emp group by deptno;

看下面:

select grouping(deptno),grouping(job),grouping_id(job), deptno, job, sum(sal) from scott.emp
 group by grouping sets(deptno, job);

最后总结

GROUP BY ROLLUP(A,B,C):首先对(A,B,C)进行GROUP BY,然后对(A,B)进行GROUP BY,然后是(A)进行GROUP BY, 最后对全表进行GROUP BY操作。
GROUP BY CUBE(A,B,C):首先对(A,B,C)进行GROUP BY,然后依次对(A,B)、(A,C)、(A)、(B,C)、(B)、(C)进行GROUP BY,最后对全表进行GROUP BY操作。
GROUP BY GROUPING SETS(A,B,C):依次对(C)、(B)、(A)进行GROUP BY结一下

数据库技术学习 https://www.itkc8.com
 



 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值