将行转换为cols

时间:2019-05-20 15:48:40

标签: sql oracle unpivot

我有下表调用fc_summary:

CALMONTH   COMP_CODE    FC10    FC20    FC30
201901     C001         550      45     100
201901     C002         50       450    10
201901     C003         150      250    120
201901     C004         520      410    10
201901     C005         30       40     105

通过它我想创建my_summary表,例如

CALMONTH   CODE     AMOUNT
201901     FC10     1300
201901     FC20     1195
201901     FC30     345

我尝试使用PIVOT实现这一目标,但无法解决

1 个答案:

答案 0 :(得分:1)

您可以使用此查询

with t(CALMONTH, COMP_CODE, FC10, FC20, FC30) as
(
 select 201901,'C001',550,45,100  from dual union all
 select 201901,'C002',50,450,10   from dual union all
 select 201901,'C003',150,250,120 from dual union all
 select 201901,'C004',520,410,10  from dual union all
 select 201901,'C005',30,40,105   from dual
)
select CALMONTH, FC as CODE, SUM(VALUE) as VALUE
  from t
 unpivot 
 (
  VALUE for FC in (FC10,FC20,FC30)
 )  
 group by CALMONTH, FC
 order by FC;

CALMONTH    CODE    VALUE
201901      FC10    1300
201901      FC20    1195
201901      FC30    345

取消显示数据