为了介绍rollup和cube用法,我将使用实际系统的期初录入表做讲解,此表三个字段分别是入库机构、入库仓库、ID,仓库是属于机构的,也就是一个机构可以对应多个仓库。所有示例将以用此表说明个函数的用法。
图一为我一个表中所有的数据。
图一:
现在为有一个需求是分别查出各机构和仓库的数据行数。
如果使用group by 实现。如下图二。
图二:
使用cube结合grouping_id替换写法,
图三:
我们来看看不使用grouping_id查询出来的结果是什么
图四:
现在有需求是,查出各机构的数据条数,并且查出各机构下面各仓库的数据条数。
用group by实现,图五:
使用rollup替换,图六:
现在我们来分别介绍cube、rollup、grouping,grouping_id的使用方法。
group by A,cube(B,C) 的结果集相当于是 group by A 、group by A,B 、group by A,C、 group by A,B ,C
select A,B,count(id) from dual group by cube(A,B)
相当于
select
A ,
count(id) from dualgroup by
A
union all
select A,B,count(id) from dual group by A,B
union all
select A,C,count(id) from dual group by A,C
union all
select A,B,C,count(id) from dual group by A,B,C
union all
group by A,rollup(B)={group by A 、group by A,B
group by A,rollup(B,C)={group by A 、group by A,B 、group by A,B ,C}
group by A,rollup(B,C,D)={group by A 、group by A,B 、group by A,B ,C、group by A,B ,C,D}
select A,B,C,count(id) from dual group by A rollup(B,C)
相当于
select
A ,
count(id) from dual group by
A
union all
select A,B,count(id) from dual group by A,B
union all
select A,B,C,count(id) from dual group by A,B,C
union all
grouping 如果遇到字段是分组字段时,返回0,否返回1
grouping_id 是在grouping基础上发展起来的,是可以对多字段进行判断,grouping_id(A,B,C) =grouping(A)*2*2+grouping(B)*2*1 +grouping(C)*2,也即是从右到左,是第
N个参数则对应的值就是2的
(N-1)次方。