工作中遇到的一個問題,記錄下我遇到的問題情況,也方面以後尋找,原文內容更詳細
原文鏈接:Oracle:Pivot 和 Unpivot 轉多列幷包含多個名稱
使用格式:
select t2.* from table1 as t1 pivot ([聚合函數] for [行轉列的條件列] in ([與“行轉列條件列”匹配]) t2;
聚合函數(sum,max,avg等),可以支持一或多個,但是需要使用別名(列:sum(t1.x1) a,sum(t1.x2) b)
行轉列的條件列,如果是需要多個列,使用concat或者||拼接成一個列
表pro_log如下:
code | qty | price | yearly | monthly |
---|---|---|---|---|
a123 | 1 | 5 | 2019 | 10 |
a123 | 2 | 7 | 2019 | 11 |
b456 | 2 | 10 | 2019 | 10 |
b456 | 3 | 4 | 2019 | 11 |
年、月拼接作爲組合條件
需要查詢 qty和qty*price的的數據並轉成列
select t2.* from (
select code,qty,qty*price as amount,yearly||monthly as y_m
from pro_log) as t1
pivot (max(t1.qty) q, max(t1.amount) a for y_m in ('201910','201911') t2;
結果:
code | '201910_q' | '201910_a' | '201911_q' | '201911_a' |
---|---|---|---|---|
a123 | 1 | 5 | 2 | 14 |
b456 | 2 | 20 | 3 | 12 |