通过一列和多个聚合的数据透视表

时间:2015-03-10 08:47:36

标签: tsql group-by sql-server-2012 pivot aggregate-functions

我准备了以下报告。它按月显示给定年份的三列(AccruedInterest,Tip& CardRevenue)。现在我想"旋转"结果使StartDate值变为12列。

我有这个:

enter image description here

我需要这个: enter image description here

我尝试过旋转表,但是我需要聚合多个列。

1 个答案:

答案 0 :(得分:0)

您必须取消数据和数据透视。 注意:我在表中添加了自己的值,以使每个值都唯一,因此您知道数据是正确的。

--Create YourTable
SELECT * INTO YourTable
FROM
(
        SELECT  CAST('2015-01-01' AS DATE) StartDate,
            607.834 AS AccruedInterest,
            1 AS Tip,
            3 AS CardRevenue
    UNION ALL
    SELECT  CAST('2015-02-01' AS DATE) StartDate,
            643.298 AS AccruedInterest,
            16.8325 AS Tip,
            5 AS CardRevenue
) A;
GO

--This pivots your data
SELECT *
FROM
(
    --This unpivots your data using cross apply
    SELECT col,val,StartDate
    FROM YourTable
    CROSS APPLY
    (
        SELECT 'AccruedInterest', CAST(AccruedInterest AS VARCHAR(100))
        UNION ALL
        SELECT 'Tip', CAST(Tip AS VARCHAR(100))
        UNION ALL
        SELECT 'CardRevenue', CAST(CardRevenue AS VARCHAR(100))
    ) A(col,val)
) B

PIVOT
(
    MAX(val) FOR startdate IN([2015-01-01],[2015-02-01])
) pvt

结果:

col               2015-01-01   2015-02-01
AccruedInterest   607.834      643.298
CardRevenue       3            5
Tip               1.0000       16.8325