在多个标准上旋转多个列

时间:2016-02-26 19:17:05

标签: sql sql-server sql-server-2012 pivot

我是SQL的新手,在我学习的过程中学习。我试图基于2个列标题来转动表格。

我当前的文件标题是年份,类型,工具,付款期,成本中心,工作类,小时,美元,单位。

我想创建一个透视表,将小时,玩偶和单位分为列,但按年份和类型。

理想的最终列标题模板为:设施,支付期,成本中心,工作类,年份 - 类型小时,年份 - 类型美元,年份 - 类型单位。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用带有CASE的SUM(或MAX,具体取决于数据类型)来动态构建列,而不是使用数据透视表。

由于您没有提供任何数据,我只是为了简洁而使用了所有数据。

--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)