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