除了使用支點,你可以用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)
你能指定你將要使用的SQL引擎嗎? –
我使用MS SQL Server Management Studio中2012 –
能否請您提供樣品輸入數據和輸出數據,並且您已經完成任何工作。 –