我有一个看起来像这样的表:
CustID Year Month Amount
------ ---- ----- ------
11 2012 12 310685
11 2013 1 312119
11 2013 2 313929
11 2013 3 315511
19 2012 12 189736
19 2013 1 195161
19 2013 2 199713
10 2013 1 448438
10 2013 2 453850
10 2013 3 460198
我需要:
Amount
与上个月Amount
的差异(如果没有'上个月',则忽略它 - 返回NULL
或0
或其他)。预期结果:
Year Month Total
---- ----- -----
2012 12 NULL
2013 1 6859 // (312119-310685) + (195161-189736) [no diff for CustID = 10 because it has no amount for 2012.12]
2013 2 11774
2013 3 7930
我尝试使用CTE和ROW_NUMBER()进行自我加入等,但是查询纠缠在一起,我迷失了方向......任何帮助都将受到赞赏。
答案 0 :(得分:0)
我认为这就是你所追求的:
WITH YearMonth
AS
(
SELECT CustID,
[Year],
[Month],
([Year] * 12 + [Month]) AS YearMonth, Amount
FROM YourTable
)
SELECT YM.[Year], YM.[Month], (YM.Amount - PREV.Amount) AS Total
FROM YearMonth YM
LEFT
JOIN YearMonth PREV
ON PREV.CustID = YM.CustID
AND PREV.YearMonth = YM.YearMonth - 1