数据库技术学习 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