oracle 行列互轉 pivot 和unpivot
阿新 • • 發佈:2019-02-10
行轉列pivot
建立表
with data_tab as(
select '1991' year,1 month,11 amount from dual union all
select '1991' year,2 month,12 amount from dual union all
select '1991' year,3 month,13 amount from dual union all
select '1991' year,4 month,14 amount from dual union all
select '1992' year,1 month,21 amount from dual union all
select '1992' year,2 month,22 amount from dual union all
select '1992' year,3 month,23 amount from dual union all
select '1992' year,4 month,24 amount from dual
)
select * from data_tab;
獲取每月資料
select year,
sum(decode(month,1,amount,0)) m1,
sum(decode(month,2,amount,0 )) m2,
sum(decode(month,3,amount,0)) m3,
sum(decode(month,4,amount,0)) m4
from data_tab
group by year;
使用pivot
將原表中一個欄位month的資料 1,2,3,4 分別作為一個新欄位,
另一個欄位amount聚合後作為新欄位的資料,
在聚合時用year欄位來group
for 原表字段/將被刪除 in (如果數值是X1 新欄位1,…如果數值是Xn 新欄位n)
sum(新欄位的資料取自原表另一個欄位)
select *
from data_tab
pivot(sum (amount) amo for month in(1 m1, 2 m2, 3 m3, 4 m4))
去掉 amo
以後
select *
from data_tab
pivot(sum(amount) for month in(1 m1, 2 m2, 3 m3, 4 m4))
增加查詢條件
select *
from data_tab
pivot(sum(amount) for month in(1 m1, 2 m2, 3 m3, 4 m4))
where year = 1991
列轉行unpivot
建立表
with tab as(
select '1991' year,11 M1,12 M2,13 M3,14 M4 from dual union all
select '1992' year,21 M1,22 M2,23 M3,24 M4 from dual )
select * from tab;
使用unpivot
將表中的幾個欄位m1,m2,…變成新的month欄位的資料
將m1,m2這幾個欄位的資料,變成新欄位amount的資料
year欄位不變
一次對每一行重複以上步驟
(新增欄位amount for 新增欄位month in (原欄位m1,m2…))
select * from tab
unpivot
(amount for month in (m1,m2,m3,m4) );
處理空欄位 include nulls
with tab as(
select '1991' year,11 M1,12 M2,13 M3,14 M4 from dual union all
select '1992' year,21 M1,22 M2,23 M3,null M4 from dual )
select * from tab
unpivot include nulls
(amount for month in (m1,m2,m3,m4) )