致梦想

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

posted on 2020-06-10 19:16  致梦想  阅读(1143)  评论(0编辑  收藏  举报

导航