我在下面的表格中有这样的数据
ID NAME TYP VALUE
== ====== ====== =======
1 JON B 123
1 JON C 456
1 JON D 789
1 JON B 545
1 JON C 295
并且需要像
这样的输出ID NAME B C D
== ====== ====== ====== ======
1 JON 123 456 789
1 JON 54 295 NULL
但是得到的输出为
ID NAME B C D
== ======= ==== === ===
1 JON 123 NULL NULL
1 JON NULL 456 NULL
1 JON NULL NULL 789
1 JON 545 NULL NULL
1 JON NULL 295 NULL
下面使用的 SQL,当我运行这个 SQL 时,我得到了额外的 NULL 行
select ID, name ,case when typ ='B' then value end B,case when typ ='C' then value end C,case when typ ='D' then value end D from table
答案 0 :(得分:1)
您可以使用聚合。 . . row_number()
:
select ID, name,
max(case when typ = 'B' then value end) as B,
max(case when typ = 'C' then value end) as C,
max(case when typ = 'D' then value end) as D
from (select t.*,
row_number() over (partition by id, name, type order by value desc) as seqnum
from table t
) t
group by id, name, seqnum