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 ;
這兩條語句是相等的。
oracle group by的擴充套件
1 rollup select job,sum sal from emp group by rollup job 將增加一行總的合計數。2 cube select job,deptno,sum sal from emp group by cube job,deptno 先按job和deptno的各種...
oracle group by 顯示其他字段
原先用select key,max value from tbl group by key 查詢出的結果,但是我要再多加乙個test欄位 根據的語句結合起來,以下是可以顯示其他字段,並且考慮排名相同的情況 select t.key t.value,listagg t.test,within grou...
oracle group by字串拼接
有一張表test,字段分別是主鍵id,road id,user id,region,現在的需求是對road id分組,然後將region欄位用逗號拼接起來 test表 分組的sql如下 select road id listagg region,within group order by road ...