Oracle group 語句探究學習筆記

來源:互聯網
上載者:User

Oracle group 語句探究學習筆記

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.