日期:2014-05-17 浏览次数:20531 次
--你的表应该有rowid字段,那么就不用row_number生成了
;WITH cte AS
(
SELECT rowid = ROW_NUMBER() OVER(ORDER BY GETDATE()), *
FROM tb
)
SELECT
借方金额,
贷方金额,
合计 = (SELECT SUM(借方金额-贷方金额) FROM cte B WHERE B.rowid <= A.rowid)
FROM cte A
WITH tt(A,B)
AS
(
SELECT 900,500
UNION ALL
SELECT 1000,600
UNION ALL
SELECT 700,200
UNION ALL
SELECT 800,300
UNION ALL
SELECT 1200,600
)
, Temp
AS
(SELECT ROW_NUMBER() OVER (ORDER BY GETDATE()) AS ID
,A,B
FROM tt)--表??
SELECT T.A
,T.B
,(T.A-T.B)+ISNULL((SELECT SUM(A-B) FROM Temp WHERE ID<T.ID ),0) AS Total
FROM Temp AS T
/*
A B Total
900 500 400
1000 600 800
700 200 1300
800 300 1800
1200 600 2400
*/