2016-02-26 36 views
0

我是新來的SQL和學習,因爲我去。我正在嘗試基於2列標題來旋轉表格。在多個標準上樞轉多列

我的當前文件標題是Year,Type,Facility,Pay Period,Cost Center,Job Class,Hours,Dollars,Units。

我想創建一個轉換表,它將小時,玩偶和單位分成若干列,但按年份和類型分列。

理想的結束列標題模板應該是:工具,薪資期間,成本中心,工作分類,年份 - 類型小時,年 - 年元,年份 - 單位單位。

謝謝!

+0

你能指定你將要使用的SQL引擎嗎? –

+0

我使用MS SQL Server Management Studio中2012 –

+0

能否請您提供樣品輸入數據和輸出數據,並且您已經完成任何工作。 –

回答

0

除了使用支點,你可以用SUM(或MAX取決於數據類型)與CASE來動態建立列。

由於您沒有提供任何數據,我只是編寫了一些並且爲了簡潔而使用了所有的整數。

--Sample Data 
CREATE TABLE #test ([Year] INT, [Type] int, Facility int, [Pay Period] int, [Cost Center] int, [Job Class] int, [Hours] int, Dollars int, Units int) 
INSERT INTO #test VALUES 
(2013, 1, 1, 1, 1, 1, 5, 10, 15), 
(2013, 2, 1, 3, 1, 1, 6, 20, 16), 
(2013, 3, 2, 1, 1, 1, 7, 30, 17), 
(2014, 1, 1, 1, 1, 1, 8, 40, 18), 
(2014, 2, 1, 3, 1, 1, 9, 50, 19), 
(2014, 3, 2, 1, 1, 1, 1, 60, 20), 
(2014, 4, 2, 3, 1, 1, 2, 70, 10), 
(2015, 1, 1, 1, 1, 1, 3, 80, 11), 
(2015, 2, 1, 3, 1, 1, 4, 90, 12), 
(2015, 3, 2, 1, 1, 1, 5, 10, 13), 
(2015, 4, 2, 3, 1, 1, 6, 20, 14), 
(2016, 1, 1, 1, 1, 1, 7, 30, 15), 
(2016, 2, 1, 3, 1, 1, 8, 40, 16), 
(2016, 3, 2, 1, 1, 1, 9, 50, 17), 
(2016, 4, 2, 3, 1, 1, 1, 60, 18) 


DECLARE @Columns NVARCHAR(MAX), 
     @Sql NVARCHAR(MAX); 

-- Build column variable using distinct Year, Type combinations for each year and type combination. 
WITH cols AS 
( SELECT y.[Year], 
      t.[Type] 
    FROM #test y, #test t 
) 
SELECT @Columns = COALESCE(@Columns + ',','') 
      + CONCAT('SUM(CASE WHEN [Year] = ',[Year],' AND [Type] = ',[Type],' THEN [Hours] END) AS ',QUOTENAME(CONCAT([Year],' ',[Type],' - Hours'))) + ',' 
      + CONCAT('SUM(CASE WHEN [Year] = ',[Year],' AND [Type] = ',[Type],' THEN [Dollars] END) AS ',QUOTENAME(CONCAT([Year],' ',[Type],' - Dollars'))) + ',' 
      + CONCAT('SUM(CASE WHEN [Year] = ',[Year],' AND [Type] = ',[Type],' THEN [Units] END) AS ',QUOTENAME(CONCAT([Year],' ',[Type],' - Units'))) 
FROM cols 
GROUP BY [Year], [Type] 
ORDER BY [Year], [Type]; 

-- Build dynamic sql that will select common fields, sum the dynamic columns, and group the data 
SET @Sql = N' 
    SELECT [Facility], [Pay Period], [Cost Center], [Job Class],' 
    + @Columns + 
    'FROM #test 
    GROUP BY [Facility], [Pay Period], [Cost Center], [Job Class] 
' 

-- Execute dyanamic query 
EXEC(@Sql)