表格:
id race
1 elf
1 troll
2 lizard
2 elf
2 human
3 dwarf
我正在寻找一个输出以下内容的请求:
id race1 race2 race3
1 elf troll
2 lizard elf human
3 dwarf
如果更容易的话,可以有n个种族或给定的最大种族数
使用SQL查询(不是pl / sql)可以吗? (如果需要特殊功能,则为Oracle)
答案 0 :(得分:1)
如果要在简单的select
中进行此操作,则可以使用条件聚合:
select id,
max(case when seqnum = 1 then race end) as race_1,
max(case when seqnum = 2 then race end) as race_2,
max(case when seqnum = 3 then race end) as race_3,
max(case when seqnum = 4 then race end) as race_4,
max(case when seqnum = 5 then race end) as race_5
from (select t.*,
row_number() over (partition by id order by id) as seqnum
from t
) t
group by id;