如何编写SQL查询以在一行中获取ID的多个值?
我有一张如下表:如何编写SQL查询以在一行中获取ID的多个值?,sql,db2,Sql,Db2,我有一张如下表: Col1 col2 1 A 1 B 我需要编写一个DB2 SQL查询以获得如下输出: Col1 col2 col3 1 A B 有什么想法吗?您可以使用聚合: select id, min(col2), max(col2) from t group by id; 理想情况下,您应该使用行编号,如下所示: Select col1 max(case when rn = 1 then col2 end) as col2,
Col1 col2
1 A
1 B
我需要编写一个DB2 SQL查询以获得如下输出:
Col1 col2 col3
1 A B
有什么想法吗?您可以使用聚合:
select id, min(col2), max(col2)
from t
group by id;
理想情况下,您应该使用
行编号
,如下所示:
Select col1
max(case when rn = 1 then col2 end) as col2,
max(case when rn = 2 then col2 end) as col3
From
(Select t.*,
Row_number() over (partirion by col1 order by col2) as rn
From t)
Group by col1
此方法允许将2个以上的列转换为行。(只需在宽恕聚合中使用
rn
)@SnehaS。你不接受这个答案有什么原因吗?