共計 1776 個字符,預計需要花費 5 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
這期內容當中丸趣 TV 小編將會給大家帶來有關如何在 Oracle 中使用 ROLLUP 分組函數,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
環境準備
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)、()
上述就是丸趣 TV 小編為大家分享的如何在 Oracle 中使用 ROLLUP 分組函數了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注丸趣 TV 行業資訊頻道。
向 AI 問一下細節