SQL Server 2008使用Pivot获取季度数据

时间:2016-06-22 05:16:51

标签: sql sql-server database pivot

我正在尝试获取每个事务的所有 NetAmount SUM ,并尝试使用Pivot显示事务的 SUM 季度的日期范围内。

{{1}}

以下是我的表格内容。

enter image description here

这是输出:

enter image description here

1 个答案:

答案 0 :(得分:2)

正如其他人所指出的那样,季度标识符应为Q1Q2Q3Q4。此外,您必须使用TransactionDate

,而不是按DATEPART(QUARTER, si.TransactionDate)进行分组
SELECT
    CustomerName,
    ISNULL([Q1],0) AS Q1,
    ISNULL([Q2],0) AS Q2,
    ISNULL([Q3],0) AS Q3,
    ISNULL([Q4],0) AS Q4
FROM
(
    SELECT sc.CustomerName, 
            SUM(si.NetAmount) AS NetAmount,
            CAST('Q' + CAST(DATEPART(QUARTER, si.TransactionDate)AS VARCHAR(MAX)) AS VARCHAR(MAX)) AS Quarterly
    FROM tblSampleSalesInvoices si
        LEFT OUTER JOIN tblSampleCustomers sc ON sc.Id = si.CustomerId
    WHERE si.TransactionDate BETWEEN @FromDate AND @ToDate
    GROUP BY sc.CustomerName, DATEPART(QUARTER, si.TransactionDate)
) AS BaseData
PIVOT
(
    SUM(NetAmount)
    FOR Quarterly IN ([Q1],[Q2],[Q3],[Q4])
)AS Pivoting

或者,您可以删除SUM子句中的GROUP BYFROM,让PIVOT处理聚合。也不需要CASTVARCHAR(MAX),使用适当的长度:

SELECT
    CustomerName,
    ISNULL([Q1],0) AS Q1,
    ISNULL([Q2],0) AS Q2,
    ISNULL([Q3],0) AS Q3,
    ISNULL([Q4],0) AS Q4
FROM
(
    SELECT
        sc.CustomerName, 
        NetAmount AS NetAmount,
        CAST('Q' + CAST(DATEPART(QUARTER, si.TransactionDate)AS VARCHAR(1)) AS VARCHAR(2)) AS Quarterly
    FROM #tblSampleSalesInvoices si
        LEFT OUTER JOIN #tblSampleCustomers sc ON sc.Id = si.CustomerId
    WHERE si.TransactionDate BETWEEN @FromDate AND @ToDate
) AS BaseData
PIVOT
(
    SUM(NetAmount)
    FOR Quarterly IN ([Q1],[Q2],[Q3],[Q4])
)AS Pivoting

ONLINE DEMO