【问题标题】:Move rows to column and columns to row in oralce SQL在oracle SQL中将行移动到列和列到行
【发布时间】:2019-10-02 18:00:47
【问题描述】:

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

【问题讨论】:

    标签: sql oracle pivot unpivot


    【解决方案1】:

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

    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;
    

    【讨论】:

    • @Gordan Linoff,感谢您的快速回答。你知道如何使用 unpivot 和 pivot 来做到这一点吗?
    • Chris Saxon 有一篇关于这个主题的优秀博客。 blogs.oracle.com/sql/…
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      相关资源
      最近更新 更多