(2.4)DDL加強功能-數據彙總grouping、rollup、cube

參考:https://www.cnblogs.com/nikyxxx/archive/2012/11/27/2791001.htmlhtml

1.rollup函數

  (1)rollup在group by 子句中使用with指定,用於生產包含小計和總計的報表(其實和excel中的分類彙總差很少)spa

  

with test as 
(
    select item = 'table' ,color = 'red' ,quantity = 100
    union all
    select item = 'table' ,color = 'greed' ,quantity = 200
    union all
    select item = 'chair' ,color = 'red' ,quantity = 300
    union all
    select item = 'chair' ,color = 'blue' ,quantity = 400
)

select item,color,sum(quantity) num from test
group by item,color with rollup

 

  分析:color爲null的都是item彙總,item爲null的是全部彙總3d

  這樣不太直觀,改一下excel

with test as 
(
    select item = 'table' ,color = 'red' ,quantity = 100
    union all
    select item = 'table' ,color = 'greed' ,quantity = 200
    union all
    select item = 'chair' ,color = 'red' ,quantity = 300
    union all
    select item = 'chair' ,color = 'blue' ,quantity = 400
)

select item,color,sum(quantity) num 
 ,grouping(item) as 'item_flag',
 grouping(color) as 'color_flag'
from test
group by item,color with rollup    

 

 咱們發現,等於1的就是彙總因而咱們能夠這樣獲得咱們想要的樣子code

with test as 
(
    select item = 'table' ,color = 'red' ,quantity = 100
    union all
    select item = 'table' ,color = 'greed' ,quantity = 200
    union all
    select item = 'chair' ,color = 'red' ,quantity = 300
    union all
    select item = 'chair' ,color = 'blue' ,quantity = 400
)

select case when grouping(item)=0 then item else '物品總計' end item,
case when grouping(color)=0 then color else '顏色小計' end color
,sum(quantity) num 
from test
group by item,color with rollup    

 

2.CUBEhtm

  和ROLLUP是同樣的,這裏就再也不深究了。blog

 

 

3.GROUPINGit

  是一個聚合函數,它產生一個附加的列,當用 CUBE 或 ROLLUP 運算符添加行時,附加的列輸出值爲1,當所添加的行不是由 CUBE 或 ROLLUP 產生時,附加列值爲0。io

僅在與包含 CUBE 或 ROLLUP 運算符的 GROUP BY 子句相聯繫的選擇列表中才容許分組。

語法

  GROUPING ( column_name )

參數

  column_name

  是 GROUP BY 子句中用於檢查 CUBE 或 ROLLUP 空值的列。

返回類型

  int

註釋

  分組用於區分由 CUBE 和 ROLLUP 返回的空值和標準的空值。做爲CUBE 或 ROLLUP 操做結果返回的 NULL 是 NULL 的特殊應用。它在結果集內做爲列的佔位符,意思是"全體"。

示例

  下面的示例將 royalty 的數值分組,並聚合 advance 的數值。GROUPING 函數應用於 royalty 列。

複製代碼
USE pubs

SELECT royalty, SUM(advance) 'total advance',

   GROUPING(royalty) 'grp'

   FROM titles

   GROUP BY royalty WITH ROLLUP
複製代碼

 

  結果集在 royalty 下顯示兩個空值。第一個 NULL 表明從表中這一列獲得的空值組。第二個 NULL 在 ROLLUP 操做所添加的彙總行中。彙總行顯示的是全部 royalty 組的 advance 合計數值,而且在 grp 列中用 1 標識。

  下面是結果集:

royalty        total advance              grp

---------      ---------------------    ---

NULL           NULL                     0 

10             57000.0000               0 

12             2275.0000                0 

14             4000.0000                0 

16             7000.0000                0 

24             25125.0000               0 

NULL           95400.0000               1 

相關文章
相關標籤/搜索