Select 多条记录作为 SQL 中的多列

Select multiple records as multiple columns in SQL

我有一个 table 看起来像这样:

ID Name
-------
1  John
1  Mary
1  Jane
2  John 
2  Mary
3  Jane

知道每个ID最多只能包含三个名字,我想用SELECT语句把它变成下面这样:

ID Name1 Name2 Name3
--------------------
1  John  Mary  Jane
2  John  Mary
3  Jane

SQL有没有办法做到这一点?

如果您知道最多有三个名字,您可以使用条件聚合来做到这一点:

select id,
       max(case when seqnum = 1 then name end) as name1,
       max(case when seqnum = 2 then name end) as name2,
       max(case when seqnum = 3 then name end) as name3
from (select t.*, row_number() over (partition by id order by name) as seqnum
      from table t
     ) t
group by id;

对于 Oracle,您可以使用 PIVOT 功能。

但是,您需要首先对您的行进行排名,通过 ID-名称对,然后您可以对刚刚生成的排名(字面意思)执行数据透视指令。

要阅读的页数: