oracle中rollup和cube使用

为了介绍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  
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  
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)次方。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值