SQL - 交换行和列

时间:2018-02-08 12:20:04

标签: sql sql-server pivot unpivot

我有一个需要交换行和列的情况。是的,我尝试使用Pivot和UnPivot,但这并没有给我预期的结果。

我的源表:

+-------+------+------+-----+-----+
| month | year | po1  | po2 | po3 |
+-------+------+------+-----+-----+
| Jan   | 2013 |  100 |  20 |  10 |
| Feb   | 2014 | 1100 | 120 | 110 |
+-------+------+------+-----+-----+

我能够制作静态转轴

select Description,value from #test
unpivot (value for Description in (year,po1, po2, po3)) unpiv;

这是我能够生成的结果

+-------------+-------+
| Description | value |
+-------------+-------+
| year        |  2013 |
| po1         |   100 |
| po2         |    20 |
| po3         |    10 |
| year        | 12013 |
| po1         |  1100 |
| po2         |   120 |
| po3         |   110 |
+-------------+-------+

预期产出:

+------+------+------+
| Desc | Jan  | Feb  |
+------+------+------+
| year | 2013 | 2014 |
| po1  |  100 | 1100 |
| po2  |   20 |  120 |
| po3  |   10 |  110 |
+------+------+------+

此外,行/列会不断变化,有没有办法让它变得动态?

1 个答案:

答案 0 :(得分:1)

这种转置是一种痛苦 - 需要转动和解开。这是一种方法:

select v.description,
       max(case when t.month = 'Jan' then v.value end) as Jan,
       max(case when t.month = 'Feb' then v.value end) as Feb
from #test t cross apply
     (values ('year', t.year), ('p01', p01), ('p02', p02), ('p03', p03)
     ) v(description, value) 
group by v.description;