Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在oralce SQL中,将行移到列,将列移到行_Sql_Oracle_Pivot_Unpivot - Fatal编程技术网

在oralce SQL中,将行移到列,将列移到行

在oralce SQL中,将行移到列,将列移到行,sql,oracle,pivot,unpivot,Sql,Oracle,Pivot,Unpivot,我从脚本中获得以下oracle SQL输出 Status Item1 Item2 Item3 Item4 Processed 22 12 10 0 Error 11 22 0 0 Unsent 10 11 0 22 我想使用PIVOT&UNPIVOT将行移动到列,将列移动到行,并在SQL中显示如下格式 Items Processed Error Unsent Item1

我从脚本中获得以下oracle SQL输出

Status     Item1 Item2 Item3 Item4
Processed     22    12    10     0
Error         11    22     0     0
Unsent        10    11     0    22
我想使用PIVOT&UNPIVOT将行移动到列,将列移动到行,并在SQL中显示如下格式

Items   Processed  Error  Unsent
Item1          22     11      10
Item2          12     22      11 
Item3          10      0       0
Item4           0      0      22

这很棘手;它需要一个解pivot和枢轴。这里有一种方法:

select item,
       sum(case when status = 'Processed' then val end) as processed,
       sum(case when status = 'Error' then val end) as error,
       sum(case when status = 'Unsent' then val end) as unsent
from ((select 'Item1' as item, status, item1 as val from t
      ) union all
      (select 'Item2' as item, status, item2 from t
      ) union all
      (select 'Item3' as item, status, item3 from t
      ) 
     ) i
group by item;

一个选项是使用条件聚合,包括
unpivot
表达式:

select items as "Items",
       max(case when status = 'Processed' then value end) as "Processed",
       max(case when status = 'Error' then value end) as "Error",
       max(case when status = 'Unsent' then value end) as "Unsent"
  from tab
unpivot (value for items in ( Item1, Item2, Item3, Item4 ))
  group by items
  order by "Items";


要先取消数据绑定,然后通过条件聚合对数据进行整理。

@Gordan Linoff,谢谢您的快速回答。你知道如何使用unpivot和pivot实现这一点吗?Chris Saxon有一个关于这个主题的优秀博客。