在 db2 中逆透视

Unpivoting in db2

我有以下table

+------+------+---+---+---+
| type | year | a | b | c |
+------+------+---+---+---+
| x    | 2015 | 1 | 1 | 1 |
| x    | 2015 | 2 | 2 | 2 |
| x    | 2017 | 3 | 3 | 3 |
| y    | 2016 | 1 | 1 | 1 |
| y    | 2017 | 2 | 2 | 2 |
| z    | 2015 | 1 | 1 | 1 |
| z    | 2016 | 3 | 3 | 3 |
+------+------+---+---+---+

预期结果必须如下

+------+------+---+---+---+
| type | year | x | y | z |
+------+------+---+---+---+
| a    | 2015 | 3 | 0 | 1 |
| a    | 2016 | 0 | 1 | 3 |
| a    | 2017 | 3 | 2 | 0 |
| b    | 2015 | 3 | 2 | 0 |
| b    | 2016 | 0 | 1 | 3 |
| b    | 2017 | 3 | 2 | 0 |
| c    | 2015 | 3 | 0 | 1 |
| c    | 2016 | 0 | 1 | 3 |
| c    | 2017 | 3 | 2 | 0 |
+------+------+---+---+---+

到目前为止,我可以编写以下查询以枢轴 table 方式使用简单的分组依据来获取结果,但我需要以逆枢轴方式显示结果,因为我的预期结果如上所示.

select type, year, sum(a) as a, sum(b) as b, sum(c) as c from table group by type,year;

上述查询的结果对我来说是一个有价值的结果,但格式不同

+------+------+---+---+---+
| type | year | a | b | c |
+------+------+---+---+---+
| x    | 2015 | 3 | 3 | 3 |
| x    | 2017 | 3 | 3 | 3 |
| y    | 2016 | 1 | 1 | 1 |
| y    | 2017 | 2 | 2 | 2 |
| z    | 2015 | 1 | 1 | 1 |
| z    | 2016 | 3 | 3 | 3 |
+------+------+---+---+---+

您可以使用 union all 取消透视,然后重新聚合:

select col_type, year,
       sum(case when type = 'x' then val end) as x,
       sum(case when type = 'y' then val end) as y,
       sum(case when type = 'z' then val end) as z
from (select type, year, 'a' as col_type, a as val from t union all
      select type, year, 'b' as col_type, b as val from t union all
      select type, year, 'c' as col_type, c as val from t 
     ) x
group by col_type, year;