欢迎进入oracle社区论坛,与200万技术人员互动交流 >>进入
grouping函数可以接受一列,返回0或者1。如果列值为空,那么grouping()返回1;如果列值非空,那么返回0。grouping只能在使用rollup或cube的查询中使用。当需要在返回空值的地方显示某个值时,grouping()就非常有用。
关于rollup和cube函数的使用,请参见我的另一篇文章。
1、在rollup中对单列使用grouping()
sql> select division_id,sum(salary)
2 from employees2
3 group by rollup(division_id)
4 order by division_id;
div sum(salary)
--- -----------
bus 1610000
ope 1320000
sal 4936000
sup 1015000
8881000
加上grouping来看看
sql> select grouping(division_id),division_id,sum(salary)
2 from employees2
3 group by rollup(division_id)
4 order by division_id;
grouping(division_id) div sum(salary)
--------------------- --- -----------
0 bus 1610000
0 ope 1320000
0 sal 4936000
0 sup 1015000
1 8881000
可以看到,为空的地方返回1,非空的地方返回0。
2、使用case转换grouping()的返回值
可能你会觉得前面的0和1太枯燥了,代表不了任何意义,说白了就是不够人性化,呵呵。这个时候我们可以使用case来转换为一些有意义的值。
sql> select
2 case grouping(division_id)
3 when 1 then 'all divisions'
4 else division_id
5 end as div,
6 sum(salary)
7 from employees2
8 group by rollup(division_id)
9 order by division_id;
div sum(salary)
------------- -----------
bus 1610000
ope 1320000
sal 4936000
sup 1015000
all divisions 8881000
3、使用case和grouping()转换多个列的值
sql> select
2 case grouping(division_id)
3 when 1 then 'all divisions'
4 else division_id
5 end as div,
6 case grouping(job_id)
7 when 1 then 'all jobs'
8 else job_id
9 end as job,
10 sum(salary)
11 from employees2
12 group by rollup(division_id,job_id)
13 order by division_id,job_id;
div job sum(salary)
------------- -------- -----------
bus mgr 530000
bus pre 800000
bus wor 280000
bus all jobs 1610000
ope eng 245000
ope mgr 805000
ope wor 270000
[1] [2]
