甲骨文的SQL:如何合并n行和结果产生额外的列?

问题描述 投票:1回答:1

表:

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

有可以是正种族或多个种族的给定的最大数量,如果它更容易

这可能与一个SQL查询(而不是PL / SQL)? (甲骨文如果需要特殊功能)

sql oracle oracle-sqldeveloper
1个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.