案例說明

將資料直的轉成橫的

假設我有資料欄位如下↓

nation,city
==============
台灣,台北
台灣,台中
台灣,高雄
日本,北海道
日本,東京
日本,大阪
美國,華盛頓
美國,波士頓
美國,紐約


--with tamp as 一個暫時的假Table,名叫tamp ,代表上面那串資料
with temp as(  
  select '台灣' nation ,'台北'      city from dual union all  
  select '台灣' nation ,'台中'      city from dual union all  
  select '台灣' nation ,'高雄'      city from dual union all 
  select '日本' nation ,'北海道' city from dual union all  
  select '日本' nation ,'東京'   city from dual union all  
  select '日本' nation ,'大阪'   city from dual union all    
  select '美國' nation ,'華盛頓' city from dual union all  
  select '美國' nation ,'波士頓' city from dual union all  
  select '美國' nation ,'紐約'   city from dual   
)  
select nation,listagg(city,'+') within GROUP (order by city) as city
from temp  
group by nation

 

執行結果如下

nation,city
=====================
台灣,台北+台中+高雄
日本,北海道+東京+大阪
美國,華盛頓+波士頓+紐約

 

補充說明

listagg(city,'+') within GROUP (order by city) as city

group by

示以group by為組別排序過的city欄位並且用「+」號相連,並將欄位名稱取名為city

文章標籤
全站熱搜
創作者介紹
創作者 我的暱稱 的頭像
我的暱稱

學習筆記

我的暱稱 發表在 痞客邦 留言(0) 人氣(4,395)