2014-02-18 41 views
0

,我有以下數據:變換行中的某些列的SQL Server

RecordYear TestA TestB TestC TestD 
2013  100 200 300 400 
2014  150 250 350 450 

我想顯示:

2013 TestType Result 2014 Test Result 
    TestA  100   TestA 150 
    TestB  200   TestB 250 
    TestC  300   TestC 350 
    TestD  400   TestD 450 

我用了unpivot到那裏一部分的方式,但我的查詢結束於:

2013 
TestA 100 
TestB 200 
TestC 300 
TestD 400 

2014 
TestA 150 
TestB 250 
TestC 350 
TestD 450 

我不知道如何移動2014年的分組,以便它在2013年組旁邊。任何幫助將不勝感激。

感謝,

+0

你可能非常接近。請花點時間提供一個腳本,以加載示例數據(或更好的http://sqlfiddle.com/#!6)以及您的查詢。 –

回答

0

,這將產生要通過使用一個CTE做支點,然後自連接的測試結果類型

WITH pv 
    AS (SELECT recordyear, 
       col, 
       val 
     FROM table1 p 
       UNPIVOT (val 
         FOR col IN (testa, 
            testb, 
            testc, 
            testd)) AS unpvt) 
SELECT a.col [2013 TestType], 
     a.val [ Result ], 
     b.col [2014 TestType], 
     b.val [ Result] 
FROM pv a 
     INNER JOIN pv b 
       ON a.col = b.col 
WHERE a.recordyear = 2013 
     AND b.recordyear = 2014 

DEMO

但是它確實有侷限性

  • 如果採取的測試不同你可能想要一個外部的喬在
  • 將無法​​正常工作,如果你想超過一年
  • 列名是硬編碼相匹配的地方
0

你可以簡單地做到這一點通過採取UNION,只是保持一個標識1 4每年的結果集加入。它的簡單

;WITH CTE1 AS 
    (
     SELECT 1 ID, RecordYear,'TESTA' TESTTYPE,TESTA Result FROM #TABLE WHERE RecordYear=2013 
     UNION ALL 
     SELECT 2 ID,RecordYear,'TESTB' TESTTYPE,TESTB Result FROM #TABLE WHERE RecordYear=2013 
     UNION ALL 
     SELECT 3 ID,RecordYear,'TESTC' TESTTYPE,TESTC Result FROM #TABLE WHERE RecordYear=2013 
     UNION ALL 
     SELECT 4 ID,RecordYear,'TESTD' TESTTYPE,TESTD Result FROM #TABLE WHERE RecordYear=2013 
    ) 
    ,CTE2 AS 
    (
     SELECT 1 ID,RecordYear,'TESTA' TEST,TESTA Result FROM #TABLE WHERE RecordYear=2014 
     UNION ALL 
     SELECT 2 ID,RecordYear,'TESTB' TEST,TESTB Result FROM #TABLE WHERE RecordYear=2014 
     UNION ALL 
     SELECT 3 ID,RecordYear,'TESTC' TEST,TESTC Result FROM #TABLE WHERE RecordYear=2014 
     UNION ALL 
     SELECT 4 ID,RecordYear,'TESTD' TEST,TESTD Result FROM #TABLE WHERE RecordYear=2014 
    ) 
    SELECT NULL '2013' ,CTE1.TESTTYPE,CTE1.Result,NULL '2014',CTE2.TEST,CTE2.Result 
    FROM CTE1 
    JOIN CTE2 ON CTE1.ID=CTE2.ID