WITH T AS (
SELECT SUM(AmountCollected) AS SubTotal, YEAR([Date]) AS Y, MONTH([Date]) AS M,
ROW_NUMBER() OVER (ORDER BY YEAR([Date]), MONTH([Date])) AS OrderID
FROM TestTable
GROUP BY YEAR([Date]), MONTH([Date])
)
SELECT Y, M, SubTotal,
(SELECT SUM(T.SubTotal) FROM T WHERE OrderID <= A.OrderID) AS RunningTotal
FROM T AS A
ORDER BY Y, M
這裏是不使用子查詢的另一個版本,這應該讓它更快一點:
WITH T AS (
SELECT SUM(AmountCollected) AS SubTotal, YEAR([Date]) AS Y, MONTH([Date]) AS M,
ROW_NUMBER() OVER (ORDER BY YEAR([Date]), MONTH([Date])) AS OrderID
FROM TestTable
GROUP BY YEAR([Date]), MONTH([Date])
)
SELECT A.Y, A.M, A.SubTotal, A.SubTotal + ISNULL(B.SubTotal, 0) AS RunningTotal
FROM T AS A
LEFT JOIN T AS B ON A.OrderID = B.OrderID + 1
ORDER BY A.Y, A.M
的RunninigTotal
場增加了當前行的SubTotal
與以前行的SubTotal
。通過不使用另一個SUM來計算RunningTotal
,您可以通過避免每行必須添加所有先前行的值來提高速度。
注意,他的作用: 內連接RunningCTE ST上s.YYYY = sr.YYYY和s.YYYYMM> = sr.YYYYMM 這意味着總將每月超過累積的,但然後每年重新開始。因此,如果您的總計不會從每年開始,那麼您可能需要對其進行調整。 –
感謝布蘭登,我已經達成了解決方案,但即使如此,我也去了你提到的例子,它增加了我的知識。感謝幫助的人!願你在職業生涯中取得很多成功! –