繁体   English   中英

如何编写 SQL 查询以在一行中获取一个 ID 的多个值?

[英]How to write a SQL query to get multiple values of an ID in one row?

我有一个如下表:

Col1 col2
1     A
1     B

我需要编写一个 DB2 SQL 查询来获取 output 如下:

Col1 col2 col3
1     A     B

有任何想法吗?

理想情况下,您应该使用row_number如下:

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

您可以使用聚合:

select id, min(col2), max(col2)
from t
group by id;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM