1、group by
group by 是分组函数,是把by后面的数据进行分组,如果后面是一个字段,就把一个字段当成一组,如果是两个字段就把两个字段当成一组,以此类推。
例如:select job,ename,sum(sal) from emp group by job,ename order by ename,job;
可以看出查出来的数据把job,ename看成一组,没有重复的。
select 后面加的字段要么是 group by 后的字段要么是被聚合函数包围的字段。(从上面可以看出group by 有消除重复的作用,但是要是只为了消除重复最好用distinct 这个快很多)
2、group by rollup
group by rollup 也是group by的一种但有和group by 不一样
例如:select job,ename,sum(sal) from emp group by rollup(job,ename) order by ename,job;
和上面的例子比较可以明显的看出 相当于select job,ename,sum(sal) from emp group by (job,ename) order by ename,job 加上
select job,sum(sal) from emp group by job order by ename,job 加上 select sum(sal) from emp;
由此可见 group by rollup(job,ename)->(job
)->全表group by 共分组n+1次 分组
3、 group by cube
例:select job,ename,sum(sal) from emp group by cube(job,ename) order by ename,job;
和上面的例子比较可以明显的看出 group by (job,ename) ,group by (ename),group by (job),全表group by
由此可见 group by rollup(job,ename)->(ename)->(job)->全表group by 共分组2n次分组
4、grouping
grouping 不是用在 group by 后面的。grouping更像是聚合函数,为了显示某条查询出的数据在,整体记录中的级别。
例:
select job,ename,sum(sal),GROUPING(job) gjob,GROUPING(ename) gename from emp group by rollup(job,ename) order by job,ename;
5、GROUPING SETS
group sets 是用在group by 后面的 相当于集合。
例如:
select job,ename,sum(sal) from emp group by GROUPING SETS (job,ename) order by ename,job;
select job,null ename,sum(sal) from emp group by job
union all
select ename,null job,sum(sal) from emp group by ename ;
这两条语句是相等的。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/27924079/viewspace-1761785/,如需转载,请注明出处,否则将追究法律责任。