在 SQL-Server 2012 中,您可以使用新添加的ROWS
orRANGE
子句:
SELECT
ID, debit, credit,
sum_debit =
SUM(debit - credit)
OVER (ORDER BY ID
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW
)
FROM
CreditData
ORDER BY
ID ;
在SQL-Fiddle中测试
我们可以在OVER(ORDER BY ID)
那里使用,结果是一样的。但是随后将使用默认值,即RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
存在效率差异(ROWS
应该首选运行总计。)
@Aaron Bertrand有一篇很棒的文章,它对计算运行总计的各种方法进行了全面测试:运行总计的最佳方法——针对 SQL Server 2012 更新
对于以前版本的 SQL-Server,您必须使用其他方法,例如自连接、递归 CTE 或游标。这是一个光标解决方案,从 Aaron 的博客中盲目复制,表格和列已针对您的问题进行了调整:
DECLARE @cd TABLE
( [ID] int PRIMARY KEY,
[debit] int,
[credit] int,
[sum_debit] int
);
DECLARE
@ID INT,
@debit INT,
@credit INT,
@RunningTotal INT = 0 ;
DECLARE c CURSOR
LOCAL STATIC FORWARD_ONLY READ_ONLY
FOR
SELECT ID, debit, credit
FROM CreditData
ORDER BY ID ;
OPEN c ;
FETCH NEXT FROM c INTO @ID, @debit, @credit ;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @RunningTotal = @RunningTotal + (@debit - @credit) ;
INSERT @cd (ID, debit, credit, sum_debit )
SELECT @ID, @debit, @credit, @RunningTotal ;
FETCH NEXT FROM c INTO @ID, @debit, @credit ;
END
CLOSE c;
DEALLOCATE c;
SELECT ID, debit, credit, sum_debit
FROM @cd
ORDER BY ID ;
在SQL-Fiddle-cursor中测试