1. 程式人生 > 資料庫 >Oracle分組函式之ROLLUP的基本用法

Oracle分組函式之ROLLUP的基本用法

rollup函式

本部落格簡單介紹一下oracle分組函式之rollup的用法,rollup函式常用於分組統計,也是屬於oracle分析函式的一種

環境準備

create table dept as select * from scott.dept;
create table emp as select * from scott.emp;

業務場景:求各部門的工資總和及其所有部門的工資總和

這裡可以用union來做,先按部門統計工資之和,然後在統計全部部門的工資之和

select a.dname,sum(b.sal)
 from scott.dept a,scott.emp b
 where a.deptno = b.deptno
 group by a.dname
union all
select null,scott.emp b
 where a.deptno = b.deptno;

上面是用union來做,然後用rollup來做,語法更簡單,而且效能更好

select a.dname,scott.emp b
 where a.deptno = b.deptno
 group by rollup(a.dname);

業務場景:基於上面的統計,再加需求,現在要看看每個部門崗位對應的工資之和

select a.dname,b.job,scott.emp b
 where a.deptno = b.deptno
 group by a.dname,b.job
union all//各部門的工資之和
select a.dname,null,scott.emp b
 where a.deptno = b.deptno
 group by a.dname
union all//所有部門工資之和
select null,scott.emp b
 where a.deptno = b.deptno;

用rollup實現,語法更簡單

select a.dname,scott.emp b
 where a.deptno = b.deptno
 group by rollup(a.dname,b.job);

假如再加個時間統計的,可以用下面sql:

select to_char(b.hiredate,'yyyy') hiredate,a.dname,scott.emp b
 where a.deptno = b.deptno
 group by rollup(to_char(b.hiredate,'yyyy'),b.job);

cube函式

select a.dname,scott.emp b
 where a.deptno = b.deptno
 group by cube(a.dname,b.job);

cube

函式是維度更細的統計,語法和rollup類似

假設有n個維度,那麼rollup會有n個聚合,cube會有2n個聚合

rollup統計列

rollup(a,b) 統計列包含:(a,b)、(a)、()

rollup(a,b,c) 統計列包含:(a,c)、(a,b)、(a)、()

....

cube統計列

cube(a,b)、(a)、(b)、()

cube(a,b)、(a,c)、(b,c)、(a)、(b)、(c)、()

....

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對我們的支援。