将行转换为列
Posted
技术标签:
【中文标题】将行转换为列【英文标题】:Convert Rows into Cols 【发布时间】:2019-05-20 15:48:40 【问题描述】:我有下表调用 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 来实现这一点,但无法解决
【问题讨论】:
您需要unpivot
。 SO上已经回答了很多类似的问题。取消透视数据后,您只需要 sum
和 group by calmonth, code
。
【参考方案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
还原您的数据
【讨论】:
以上是关于将行转换为列的主要内容,如果未能解决你的问题,请参考以下文章