答案 0 :(得分:2)
正如其他人所指出的那样,季度标识符应为Q1
,Q2
,Q3
和Q4
。此外,您必须使用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 BY
和FROM
,让PIVOT
处理聚合。也不需要CAST
到VARCHAR(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