您的位置:首页 > 其它

group by rollup 和grouping的使用实例

2013-06-18 10:49 274 查看
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));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: