【Oracle】多行數據合並為一行,使用逗號分隔


現有emp表,表結構如下:

1.需求描述

現在需要將表emp的字段按照字段順序依次拼接為一行,最終效果如下:

2.實現方法

2.1 通過listagg函數實現

select a.table_name,listagg(column_name,',') within group(order by column_id) as res
from user_tab_columns a where table_name='EMP'
group by a.table_name;

2.2 通過wmsys.wm_concat實現

首先,我們使用常規的寫法

select a.table_name, wmsys.wm_concat(a.column_name) 
from user_tab_columns a where table_name='EMP'
group by a.table_name;

執行結果如下圖:

從結果可以清晰的發現,上述結果雖然連接在一起了,但是並沒有按照字段順序排序,那么需要排序的話,就得添加over

select table_name, max(res) from (
select a.table_name, 
wmsys.wm_concat(a.column_name) over(partition by a.table_name order by a.column_id) as res
from user_tab_columns a where table_name='EMP')
group by  table_name;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM