1. 程式人生 > >Oracle 列轉行函式 Listagg()

Oracle 列轉行函式 Listagg()

最基礎的用法:

LISTAGG(XXX,XXX) WITHIN GROUP( ORDER BY XXX)

例如有這樣一張表:

FID    FType   FName

1       DB      MySQL

1       DB      Oracle

現在我們需要得到以下結果:

FID    FType   FName

1       DB      MySQL,Oracle

這個查詢結果其實很好實現,在Oracle 11g中為我們提供了Listagg函式,下面就是查詢語句:

SELECT FID, FType,LISTAGG(FName, ‘,’) WITHIN GROUP (ORDER BY FName) AS FName
FROM TABLENAME
GROUP BY FID


用法就像聚合函式一樣,通過Group by語句,把每個Group的一個欄位,拼接起來。

非常方便。

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  

同樣是聚合函式,還有一個高階用法:

就是over(partition by XXX)

也就是說,在你不實用Group by語句時候,也可以使用LISTAGG函式:

with temp as(  
  select 500 population, 'China' nation ,'Guangzhou' city from dual union all  
  select 1500 population, 'China' nation ,'Shanghai' city from dual union all  
  select 500 population, 'China' nation ,'Beijing' city from dual union all  
  select 1000 population, 'USA' nation ,'New York' city from dual union all  
  select 500 population, 'USA' nation ,'Bostom' city from dual union all  
  select 500 population, 'Japan' nation ,'Tokyo' city from dual   
)  
select population,  
       nation,  
       city,  
       listagg(city,',') within GROUP (order by city) over (partition by nation) rank  
from temp