繁体   English   中英

在 ORACLE SQL 中将一组列转换为行

[英]Convert a set of columns into rows in ORACLE SQL

我有一个查询,它返回一个看起来有点像下面的表。

在图像中,我希望输入表看起来像输出表——

本质上,我希望将列中的所有数据转置为行。 但我不想将行转换为列。

我已经看到了转置行和列的解决方案,但想检查是否有任何人都知道的更简单的方法。 任何帮助表示赞赏!

TIA

在此处输入图片说明

就像您已经知道需要将rows转换为columns PIVOT ,类似地将columns转换为rows我们需要UNPIVOT

由于没有指定列名的特定表,我使用WITH子句创建了一个临时表来演示。是了解有关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 中,我建议使用横向连接来取消旋转表。 假设列名为hour0hour1hour2 、...,这将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM