Oracle分組函數之ROLLUP的基本用法
rollup函數
本博客簡單介紹一下oracle分組函數之rollup的用法,rollup函數常用于分組統(tǒng)計,也是屬于oracle分析函數的一種
環(huán)境準備
create table dept as select * from scott.dept; create table emp as select * from scott.emp;
業(yè)務場景:求各部門的工資總和及其所有部門的工資總和
這里可以用union來做,先按部門統(tǒng)計工資之和,然后在統(tǒng)計全部部門的工資之和
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, sum(b.sal) from scott.dept a, scott.emp b where a.deptno = b.deptno;
上面是用union來做,然后用rollup來做,語法更簡單,而且性能更好
select a.dname, sum(b.sal) from scott.dept a, scott.emp b where a.deptno = b.deptno group by rollup(a.dname);

業(yè)務場景:基于上面的統(tǒng)計,再加需求,現在要看看每個部門崗位對應的工資之和
select a.dname, b.job, sum(b.sal) from scott.dept a, scott.emp b where a.deptno = b.deptno group by a.dname, b.job union all//各部門的工資之和 select a.dname, null, sum(b.sal) from scott.dept a, scott.emp b where a.deptno = b.deptno group by a.dname union all//所有部門工資之和 select null, null, sum(b.sal) from scott.dept a, scott.emp b where a.deptno = b.deptno;
用rollup實現,語法更簡單
select a.dname, b.job, sum(b.sal) from scott.dept a, scott.emp b where a.deptno = b.deptno group by rollup(a.dname, b.job);

假如再加個時間統(tǒng)計的,可以用下面sql:
select to_char(b.hiredate, 'yyyy') hiredate, a.dname, b.job, sum(b.sal) from scott.dept a, scott.emp b where a.deptno = b.deptno group by rollup(to_char(b.hiredate, 'yyyy'), a.dname, b.job);
cube函數
select a.dname, b.job, sum(b.sal) from scott.dept a, scott.emp b where a.deptno = b.deptno group by cube(a.dname, b.job);
cube
函數是維度更細的統(tǒng)計,語法和rollup類似
假設有n個維度,那么rollup會有n個聚合,cube會有2n個聚合
rollup統(tǒng)計列
rollup(a,b) 統(tǒng)計列包含:(a,b)、(a)、()
rollup(a,b,c) 統(tǒng)計列包含:(a,b,c)、(a,b)、(a)、()
....
cube統(tǒng)計列
cube(a,b) 統(tǒng)計列包含:(a,b)、(a)、(b)、()
cube(a,b,c) 統(tǒng)計列包含:(a,b,c)、(a,b)、(a,c)、(b,c)、(a)、(b)、(c)、()
....
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
相關文章
Oracle平臺應用數據庫系統(tǒng)的設計與開發(fā)
Oracle平臺應用數據庫系統(tǒng)的設計與開發(fā)...2007-03-03
Oracle多行數據合并為一行數據并將列數據轉為字段名三種方式
怎么合并多行記錄的字符串,一直是oracle新手喜歡問的SQL問題之一,下面這篇文章主要給大家介紹了關于Oracle多行數據合并為一行數據并將列數據轉為字段名的三種方式,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-06-06
解讀Oracle中代替like進行模糊查詢的方法instr(更高效)
這篇文章主要介紹了解讀Oracle中代替like進行模糊查詢的方法instr(更高效),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11

