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 dualunion 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));