Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何编写SQL查询以在一行中获取ID的多个值?_Sql_Db2 - Fatal编程技术网

如何编写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。你不接受这个答案有什么原因吗?