group by rollup 和grouping的使用實例

GROUPING函數可以接受一列,返回0或者1。如果列值爲空,那麼GROUPING()返回1;如果列值非空,那麼返回0。GROUPING只能在使用ROLLUP或CUBE的查詢中使用。當需要在返回空值的地方顯示某個值時,GROUPING()就非常有用。

用下面的sql執行一下,就可以知道group by rollup和grouping的用法

with a as (select 'dev1' col1,'file1' col2,'aa' col3,'bb' col4,1 col5 from dual 

  union all select 'dev1' col1,'file2' col2,'cc' col3,'dd' col4,3 col5 from dual
  union all select 'dev2' col1,'file3' col2,'ee' col3,'ff' col4,7 col5 from dual 
  union all select 'dev2' col1,'file4' col2,'gg' col3,'hh' col4,4 col5 from dual
  )
select case  when grouping(col1)=1 and grouping(col2)=1 then '總計' when grouping(col2)=1 then '合計' else col1 end as col_1,
       case grouping(col2) when 1 then '- -' else col2 end as col_2,
       case grouping(col3) when 1 then '- -' else col3 end as col_3,
       case grouping(col4) when 1 then '- -' else col4 end as col_4,
       sum(col5)
from a
group by rollup(col1,(col2,col3,col4));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章