Oracle SQL - 将行显示为列 - 多对多关系

Oracle SQL - Display rows as columns - Many to Many Relationship

美好的一天!如果我想在 Oracle SQL.

中实际可行,我需要一些指导

我有一个 table 这样的:

ID Name Code
999 Abby 1
999 Betty 1
999 Cass 2
999 Diane 2
999 Elly 2
999 Faye 3
999 Greg 4
999 Honey 4
999 Iman 4
999 Jam 4
999 Klade 5

我想实现这样的目标:

ID 1 2 3 4 5
999 Abby Cass Faye Greg Klade
999 Betty Dianne Honey
999 Elly Iman
999 Jam `

我已经尝试过联接、枢轴、聚合,但似乎没有任何效果(据我尝试过。) 我什至尝试获取所有原始数据并创建一个新的 table,但我唯一可以引用它们的 ID 是 ID。

请帮忙。 任何正确方向的想法或参考或资源将不胜感激!

提前致谢!

转轴是一种选择。

  select *
  from (select id, name, code,
        row_number() over (partition by code order by name) rn
        from test
       )
  pivot
    (listagg(name, '') within group (order by null) val
     for code in (1, 2, 3, 4, 5)
    );

这导致

        ID         RN 1_VAL      2_VAL      3_VAL      4_VAL      5_VAL
---------- ---------- ---------- ---------- ---------- ---------- ----------
       999          1 Abby       Cass       Faye       Greg       Klade
       999          2 Betty      Diane                 Honey
       999          3            Elly                  Iman
       999          4                                  Jam

关键思想是使用row_number(),但我更喜欢条件聚合:

select code,
       max(case when code = 1 then name end) as code_1,
       max(case when code = 2 then name end) as code_2,
       max(case when code = 3 then name end) as code_3,
       max(case when code = 4 then name end) as code_4,
       max(case when code = 5 then name end) as code_5
from (select t.*,
             row_number() over (partition by id, code order by name) as seqnum
      from t
     )
group by id, seqnum