1. 程式人生 > >Oracle中將查詢出的多條記錄的某個欄位拼接成一個字串的方法

Oracle中將查詢出的多條記錄的某個欄位拼接成一個字串的方法

http://zhidao.baidu.com/link?url=PQfRn7OH1XlZmCeQNT-Uofy00geAzvSpoDZ-B70rF33_TIcCCkRfCBfvOZtbZOq4V9areNdYt4KvF4oS9unZfyFBScPCKBwGKprlVy7jHWa
with temp as(  
  select 'China' nation ,'Guangzhou' city from dual union all  
  select 'China' nation ,'Shanghai' city from dual union all  
  select 'China' nation ,'Beijing' city from dual union all  
  select 'USA' nation ,'New York' city from dual union all  
  select 'USA' nation ,'Bostom' city from dual union all  
  select 'Japan' nation ,'Tokyo' city from dual   
)  
select nation,listagg(city,',') within GROUP (order by city)  
from temp  
group by nation 

這是最基礎的用法:
LISTAGG(XXX,XXX) WITHIN GROUP( ORDER BY XXX)
 
用法就像
聚合函式
一樣,通過Group by語句,把每個Group的一個欄位,拼接起來。

非常方便

可以考慮使用wmsys.wm_concat方法,該方法是將記錄的值使用逗號間隔拼接
使用方法如下:
select t.rank, WMSYS.WM_CONCAT(t.Name) TIME From t_menu_item t GROUP BY t.rank;

select id,wmsys.wm_concat(name) over (order by id) name from idtable;