oracle 列轉行 listagg()函數 詳解

listagg() :   Oracle的列轉行函數;

版本要求: 11.2 以上版本.

語法: 

listagg(iw.wfl_id,',') within group(order by ir.serno)

listagg(列名,' 分割符號') within group(order by 列值被拼接的順序)

分組函數:

用法1:

select distinct ir.serno,ir.code,
LISTAGG(iw.wfl_id,',') within group(order by ir.serno) over (partition by ir.serno) wfl_name

from iqp_me_refuse_reasion ir, Iqp_ref_Wfl_Node iw 
where ir.serno = iw.reason_id;

用法2:

select ir.serno,ir.code,
LISTAGG(iw.wfl_id,',') within group(order by ir.serno) wfl_name

from iqp_me_refuse_reasion ir, Iqp_ref_Wfl_Node iw 
where ir.serno = iw.reason_id
group by ir.serno,ir.code;

得到結果集相同.

區別:

group by 後的列必須是查詢的分組全部列.

partition by 查出的結果集是重複的,需要使用 distinct 進行顯式去重.

對於查詢結果非常複雜的業務場景,個人感覺使用 PARTITION BY 會更靈活一些;GROUP BY 由於其查詢結果列必須出現在 GROUP BY 條件裏邊而顯得有些臃腫,不夠優雅。

partition by 可以理解爲以什麼來分區.

同 wm_concat() 函數的區別:

select ir.serno,ir.code,
to_char(wm_concat(iw.wfl_id)) wfl_name
from iqp_me_refuse_reasion ir, Iqp_ref_Wfl_Node iw 
where ir.serno = iw.reason_id
group by ir.serno,ir.code;

使用 wm_concat 函數,記得加上to_char. 不然會展現成 CLOB 字段.

個人建議: 11g 版本後使用 listagg 函數. 之前版本使用 wm_concat 函數.

以上結果集都是一樣:

-- 工作中用到,查閱資料後分享.

轉載請說明出處.

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章