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, 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);

在這里插入圖片描述

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

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);

在這里插入圖片描述
假如再加個時間統計的,可以用下面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函數是維度更細的統計,語法和rollup類似

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

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

  • cube統計列
    cube(a,b) 統計列包含:(a,b)、(a)、(b)、()
    cube(a,b,c) 統計列包含:(a,b,c)、(a,b)、(a,c)、(b,c)、(a)、(b)、(c)、()
    ....


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM