DB2多行多列轉一行多列


最近有個需求是將DB2中多行多列轉一行多列,

如:

id  key  value

1  key1   A

1  key2   B

2  key1   C

需要轉成:

id  key1  key2

1  A    B

2  C    null

一開始找了一個DB2的函數listagg,但這個函數只能將列的值合並,不能起到想要的效果,但是可以參考:https://blog.csdn.net/zejunwzj/article/details/84061315

於是又找了一個https://www.csdn.net/gather_2e/MtTaEgwsNTg0NS1ibG9n.html

直接貼過來,要注意,[temp]這種形式不正確,要去掉[],另外要加上max,不然會報錯

select 
max(case when name='1' then [temp] else null end) as temp1
, max(case when name='2' then [temp] else null end) as temp2,
 max(case when name='3' then [temp] else null end) as temp3 
from historyt group by time

group by需要配合聚合函數,參考:https://www.cnblogs.com/woshimrf/p/4788491.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM