问题描述
在图像中,我希望输入表看起来像输出表-
本质上,我希望列中的所有数据转置成行。但是我不想将行转换为列。
我已经看到了解决行和列转置的解决方案,但是我想检查是否存在任何人都知道的更简单的东西。任何帮助表示赞赏!
TIA
解决方法
就像您已经知道将rows
转换为columns
PIVOT
一样,类似地,将columns
转换为rows
也需要UNPIVOT
。
由于没有指定列名的特定表,因此我使用了WITH
子句来创建一个临时表进行演示。 Here的链接可进一步了解UNPIVOT
中使用的条款,供您参考。
with table1
as
(
select 'Inbound' department,50 hour0,44 hour1,29 hour2,47 hour3,17 hour4 from dual
union all
select 'Outbound',6,4,10,24,39 from dual
union all
select 'Returns',3,1,39,43,35 from dual
)
select *
from table1 t1
unpivot (value for hour in (hour0 as '0',hour1 as '1',hour2 as '2',hour3 as '3',hour4 as '4'))
,
在Oracle中,我建议使用横向联接来取消透视表。假设这些列分别称为hour0
,hour1
,hour2
,...,则表示为:
select t.department,x.*
from mytable t
cross apply (
select 0 as hour,t.hour0 as value from dual
union all select 1,t.hour1 from dual
union all select 2,t.hour2 from dual
union all ...
) x