oracle--rollup 和cube分組累計求和

來源:互聯網
上載者:User

group by 語句支援基本的having條件,還支援rollup和cube提供資訊匯總功能,類似小計。

rollup:縱向小計,從右向左逐個對每一列進行小結並在結果中產生獨立的一行。只返回第一個分組條件指定的列的統計行。

cube:橫行小計

  1. select d.deptno,t.job,sum(t.sal) from emp t,dept d   
  2. where t.deptno=d.deptno   
  3. group by rollup(d.deptno,t.job)  

執行結果:

***

使用grouping_id顯示指定的分組層級的記錄。返回grouping()位向量的十進位值,GROUPING位向量的計算方法是將按照順序對每一列調用GROUPING函數的結果組合起來。

例:grouping_id(a,b,c),a為空白就是0非空為1,b和c也一樣,結果會得到一個三位元,用二進位轉換成十進位就是了,a,b,c全是非空,即111就是7,三列就是7,如果是兩列自然是11就是3

select ... from 表 group by rollup(.....) having grouping_id(....)<=1

rollup(x,y)2列 rollup(x,y,z)3列
總計是grouping_id=3 總計是grouping_id=7
小計grouping_id=1 小計grouping_id=3
記錄是grouping_id=0 記錄是grouping_id=0

此時要求不顯示最後合計列:

  1. select d.deptno,t.job,sum(t.sal) from emp t,dept d   
  2. where t.deptno=d.deptno   
  3. group by rollup(d.deptno,t.job)having grouping_id(d.deptno,t.job)<=1  

執行結果:

實際情況中要展示結果集中匯總列加上小計和合計,此時這樣處理:

執行結果:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.