【问题标题】:Oracle SQL: how to merge n lines and create additional columns in result?Oracle SQL:如何合并 n 行并在结果中创建附加列?
【发布时间】:2019-02-05 02:47:41
【问题描述】:

表:

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 如果需要特殊功能)

【问题讨论】:

  • SQL 查询具有固定数量的已定义列。你只能用动态 SQL (execute immediate) 做你想做的事。
  • @GordonLinoff 好的,假设最多有 5 场比赛,有可能吗?
  • @KaushikNayak 我不是在寻找 pl/sql,而是在寻找 sql 请求。我会在问题中说得更清楚
  • 如果它的列数未知,那么除非您想要 XML 输出,否则纯 sql 解决方案将是不可能的。使用固定列,您可以

标签: sql oracle oracle-sqldeveloper


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2021-04-10
    相关资源
    最近更新 更多