oracle group 语句探究(笔记)

来源:互联网 发布:淘宝商品自动下架了 编辑:程序博客网 时间:2024/06/04 23:10

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    null10 1        null11 null    212 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      name11 null    null12 null    213 14 15 with test as16 (17     select 1 id,2 name from dual18 )19 select id,name from test 20 group by cube(id,name) 21 having grouping(id)=0;22 23 输出结果为24 id      name25 1        null26 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_212       from test   13       group by cube(id,name)14 )15 select16     gid,id_1||name_1 dn,id_2,name_217 from18 cuded;19 20 结果为:21 gid        dn        id_2        name_222 0          00   23 1          01                    name 224 2          10       id 125 3          11       id 1         name 226         
复制代码

0 0
原创粉丝点击