2016-04-25 14 views
0

我有一個CSV文件看起來像這樣導入的數據:SQL支點 - 試圖第一行轉換爲列

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

PIVOT a UNPIVOT表。步驟:

  1. 重命名錶中的列
  2. UNPIVOT逐年
  3. PIVOT通過現場

完整的查詢:

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]