0

我从我的脚本中得到以下 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
4

2 回答 2

0

一种选择是使用条件聚合,包括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";

Demo

首先对数据进行反透视,然后通过条件聚合将它们整理起来。

于 2019-10-02T19:04:30.617 回答
0

这很棘手;它需要一个非枢轴和枢轴。这是一种方法:

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;
于 2019-10-02T18:04:43.190 回答