转自:http://blog.csdn.net/cunxiyuan108/article/details/21951377
为了方便大家学习和测试,所有的例子都是在Oracle自带用户Scott下建立的。
现在客户的需求是统计部门中每种工作的工资总额,最后还需要统计所有人的工资总数,相信这样的需求对大家来说还是比较简单的,很快就能写出SQL语句,如下:
- select deptno, job, sum(sal)
- from scott.emp
- group by deptno, job
- order by deptno
- union all
- select null deptno, null job, sum(sal) from scott.emp;
- 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);
- 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;
- 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。