Home > Database > Mysql Tutorial > body text

Oracle group 语句探究学习笔记

WBOY
Release: 2016-06-07 16:33:41
Original
1029 people have browsed it

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

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

2、group by 的cube扩展

with test as
(
    select 1 id,2 name from dual
)
select id,name from test group by cube(id,name);

输出结果为
id      name
null    null
1        null
null    2
1        2

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

3、grouping()函数

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

with test as
(
    select 1 id,2 name from dual
)
select id,name from test
group by cube(id,name)
having grouping(id)=1;

输出结果为
id      name
null    null
null    2


with test as
(
    select 1 id,2 name from dual
)
select id,name from test
group by cube(id,name)
having grouping(id)=0;

输出结果为
id      name
1        null
1        2

4、grouping_id()函数

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

with test as
(
    select 1 id,2 name from dual
),
cuded as(
    select
        grouping_id(id,name) gid,
        to_char(grouping(id)) id_1,
        to_char(grouping(name)) name_1,
        decode(grouping(id),1,' id 1') id_2,
        decode(grouping(name),1,' name 2') name_2
      from test 
      group by cube(id,name)
)
select
    gid,id_1||name_1 dn,id_2,name_2
from
cuded;

结果为:
gid        dn        id_2        name_2
0          00 
1          01                    name 2
2          10      id 1
3          11      id 1        name 2

本文永久更新链接地址:

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template