【问题标题】:Oracle - Transpose rows into columns [duplicate]Oracle - 将行转换为列[重复]
【发布时间】:2019-10-14 22:29:01
【问题描述】:

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

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

我怎样才能实现这一点(枢轴和/或分析功能)?

非常感谢任何帮助。

【问题讨论】:

    标签: oracle oracle11g pivot


    【解决方案1】:

    您可以使用 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 
    

    【讨论】:

      【解决方案2】:

      如果您不需要动态列名,您可以使用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

      【讨论】:

        猜你喜欢
        • 2020-02-23
        • 2014-01-27
        • 1970-01-01
        • 2021-03-02
        • 2021-08-07
        • 2018-11-11
        • 2019-09-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多