Oracle-将行转置为列

时间:2019-05-29 10:26:14

标签: oracle oracle11g pivot

这是我一直在处理的表中的示例:

CREATE TABLE TEST_MC
(
 CLUSTER_K INTEGER,
 PROCESS_PHASE INTEGER,
 SEM_AGG CHAR(1)
);

CLUSTER_K  PROCESS_PHASE   SEM_AGG
==================================
    328          1            M
----------------------------------
    328          2            A
----------------------------------
    328          3            A

现在,我想对行进行转置和折叠,以获得以下结果:

 CLUSTER_K  SEM_AGG_1   SEM_AGG_2   SEM_AGG_3
=============================================
    328         M           A           A

我如何实现这一点(枢轴和/或分析功能)?

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用GROUP BY:

select CLUSTER_K,
  max(case when PROCESS_PHASE=1 then SEM_AGG else null end) SEM_AGG_1,
  max(case when PROCESS_PHASE=2 then SEM_AGG else null end) SEM_AGG_2,
  max(case when PROCESS_PHASE=3 then SEM_AGG else null end) SEM_AGG_3
from test_mc
group by CLUSTER_K 

答案 1 :(得分:0)

如果您不需要动态列名,则可以使用Pivot

with tab as(
  select 328 as CLUSTER_K, 1 as process_phase, 'M' as sem_agg from dual union all
  select 328 as CLUSTER_K, 2 as process_phase, 'A' as sem_agg from dual union all
  select 328 as CLUSTER_K, 3 as process_phase, 'A' as sem_agg from dual
)
select  *
from tab 
pivot (max(sem_agg) for process_phase in (1 as sem_agg_1, 2 as sem_agg_2, 3 as sem_agg_3))

db <>提琴here