Oracle Pivot-多级转换

时间:2019-03-01 07:25:21

标签: sql oracle oracle11g pivot

我有以下数据

C1  C2  C3  c4

1   C   1   2
1   M   0   2
2   C   2   3
2   M   4   3

我希望将此作为

C1  C2  C3  C4  C5
#   C   C   M   M
1   1   2   0   2
2   2   3   4   3

我该如何实现?

逻辑: 应始终将其分组为C1级别。 C2数据将成为C3和C4中数据的列标题。

1 个答案:

答案 0 :(得分:1)

您可以在以下查询中使用条件聚合:

with t(C1, C2, C3, C4) as
(
 select 1,'C',1,2 from dual union all
 select 1,'M',0,2 from dual union all
 select 2,'C',2,3 from dual union all
 select 2,'M',4,3 from dual   
)
  select null as C1, min(C2) as C2, min(C2) as C3, max(C2) as C4, max(C2) as C5
    from t
  union all  
  select C1, 
         to_char(sum(case when C2='C' then C3 end)),
         to_char(sum(case when C2='C' then C4 end)),
         to_char(sum(case when C2='M' then C3 end)),
         to_char(sum(case when C2='M' then C4 end))
    from t
   group by C1;

 C1  C2  C3  C4  C5
 --  --  --  --  --
     C   C   M   M
 1   1   2   0   2
 2   2   3   4   3