oracle group 语句探究(笔记)

1、group by语句在oracle中没有排序功能,必须依靠order by才能实现按照预定结果的排序

2、group by 的cube扩展

复制代码
 1 with test as
 2 (
 3     select 1 id,2 name from dual
 4 )
 5 select id,name from test group by cube(id,name);
 6 
 7 输出结果为
 8 id      name
 9 null    null
10 1        null
11 null    2
12 1        2
复制代码

 

由此不难看出group by cube的作用是把null引入做一个笛卡尔积,最终显示出来,在有些情况下用起来非常的方便,在某些情况下可以替代union all,极高的提升效率。其中在数据量比较多的情况下,全空列只出现一次

3、grouping()函数

grouping() 与cube一起使用,用来判断这个值是不是聚合产生的null值,如果是返回1,不是返回零

复制代码
 1 with test as
 2 (
 3     select 1 id,2 name from dual
 4 )
 5 select id,name from test 
 6 group by cube(id,name) 
 7 having grouping(id)=1;
 8 
 9 输出结果为
10 id      name
11 null    null
12 null    2
13 
14 
15 with test as
16 (
17     select 1 id,2 name from dual
18 )
19 select id,name from test 
20 group by cube(id,name) 
21 having grouping(id)=0;
22 
23 输出结果为
24 id      name
25 1        null
26 1        2
复制代码

4、grouping_id()函数

grouping_id()在某种程度上与grouping()相似,不同的在于grouping()计算一个表达式返回0或1,而group_id()计算一个表达式,确定其参数中的哪一行被用来生成超聚合行,然后常见一个矢量,并将该值作为整型值返回

复制代码
 1 with test as
 2 (
 3     select 1 id,2 name from dual
 4 ),
 5 cuded as(
 6     select 
 7         grouping_id(id,name) gid,
 8         to_char(grouping(id)) id_1,
 9         to_char(grouping(name)) name_1,
10         decode(grouping(id),1,' id 1') id_2,
11         decode(grouping(name),1,' name 2') name_2
12       from test   
13       group by cube(id,name)
14 )
15 select
16     gid,id_1||name_1 dn,id_2,name_2
17 from
18 cuded;
19 
20 结果为:
21 gid        dn        id_2        name_2
22 0          00   
23 1          01                    name 2
24 2          10       id 1
25 3          11       id 1         name 2
26         
复制代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值