Oracle 根据一列将行转换为动态列

Oracle convert rows into dynamic columns based on one column

我有什么

具有以下数据的 Oracle table

COL1  COL2
----  ----
1001  110
1001  111
1001  112
2001  210
2001  211

我要的是

1001  110  111  112
2001  210  210

基本上我想要 COL2 中与同一行上的 COL1 匹配的所有值。

如何在 Oracle 中实现这一点? 请注意,列数应根据可用的匹配行而增加。 如果那不可能,那么我们可以考虑最多 5 个值。

最简单的方法是使用 list_agg():

将它们放在一列中
select col1, listagg(col2, ' ') within group (order by col2) as col2s
from t
group by col1;

对于单独的列,我会推荐 row_number() 和条件聚合:

select col1,
       max(case when seqnum = 1 then col2 end) as col2_1,
       max(case when seqnum = 2 then col2 end) as col2_2,
       max(case when seqnum = 3 then col2 end) as col2_3
from (select t.*, row_number() over (partition by col1 order by col2) as seqnum
      from t
     ) t
group by col1;