联接2个表时,Oracle将重复的行划分为列

时间:2019-02-05 21:31:00

标签: sql oracle

我有2张这样的桌子:

table_a

id  col2
1   A
1   B
2   A
2   B
3   B

table_b

id  col1
1    X
2    Y
3    Z

我想连接两个表,以使结果包含table_a的col2中的重复行值作为列。每个ID最多包含3个table_a.col2值。在此示例中,结果表将如下所示:

结果:

id col1 col2 col3 col 4
1   X    A    B    null
2   Y    A    B    null
3   Z    B    null null

我该如何实现?我知道我可以使用listagg()将所有行聚合为这样的一列:

 select b.id, b.col1,
 listagg(a.col2, '_') within group (order by a.col2) as col2
 from table_b b join
 table_a a
 on b.id = a.id
 group by b.id, b.col1;

这会给我这样的结果:

id col1 col2
1   X    A_B
2   Y    A_B
3   Z    B

1 个答案:

答案 0 :(得分:4)

您可以使用条件聚合:

select b.id, b.col1,
       max(case when seqnum = 1 then a.col2 end) as col2,
       max(case when seqnum = 2 then a.col2 end) as col3,
       max(case when seqnum = 3 then a.col2 end) as col4
 from table_b b left join
      (select a.*,
              row_number() over (partition by a.id order by a.col2) as seqnum
       from table_a a
      ) a
      on b.id = a.id
 group by b.id, b.col1;