SQL pivot - 尝试将第一行转换为列

时间:2016-04-25 04:14:55

标签: sql-server

我从csv文件导入的数据如下所示:

Name     Field     Year01     Year02 ... Year10
-----------------------------------------------
name     fieldname 2006       2007   ... 2015
xyz      field_a   123        999        222
xyz      field_b   111.1      123.4      456.7
abc      field_a   444        555        890
abc      field_b   999.9      888.8      789.0

我需要看起来像这样:

name  year   field_a   field_b
-----------------------------------------------
xyz   2006   123       111.1
xyz   2007   999       123.4
xyz   2015   222       456.7
...
abc   2006   444       999.9
abc   2007   555       888.8
abc   2015   890       789.0

我确定使用Pivot指令可以做到这一点,但似乎无法使其正常工作。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

PIVOT一个UNPIVOT表。步骤进行:

  1. 重命名表格列
  2. UNPIVOT年份
  3. PIVOT字段
  4. 完整查询:

        WITH T1 AS
        (
            SELECT *
            FROM (VALUES 
                ('name', 'fieldname', 2006, 2007, 2015), 
                ('xyz', 'field_a', 123  ,999  ,222  ),
                ('xyz', 'field_b', 111.1,123.4,456.7),
                ('abc', 'field_a', 444  ,555  ,890  ),
                ('abc', 'field_b', 999.9,888.8,789.0)
            ) AS T(Name,     Field,     Year01,     Year02, Year10)
        )
        SELECT *
        FROM 
        (
            SELECT Name AS name, Field AS fieldname, Year01 AS [2006], Year02 AS [2007], Year10 AS [2015]
            FROM T1
            WHERE Name <> 'name'
        ) AS T2
        UNPIVOT
        (
            [value] FOR [year] in ([2006], [2007], [2015])
        ) AS UP
        PIVOT
        (
            MIN(value) FOR fieldname in (field_a, field_b)
        ) AS P
        ORDER BY name desc, [year]