表格如下:
| Date | Amount | |-----------------------| | 2014-02-02 | -500 | | 2014-03-05 | 15 | | 2014-03-25 | 20 | | 2014-04-14 | 12 | | 2014-04-30 | -200 |
是否存在可以产生如下输出的查询:
| Date | Amount | Balance | |-----------------------------------| | 2014-02-02 | -500 | -500 | | 2014-03-05 | 15 | -485 | | 2014-03-25 | 20 | -465 | | 2014-04-14 | 12 | -453 | | 2014-04-30 | -200 | -653 |
我需要获得每笔交易的余额。请帮帮我们。谢谢
答案 0 :(得分:0)
这应该可以解决问题:
select main.Date,main.Amount,grp.balance
from @T1 main inner join (
SELECT x.Date
, SUM(y.Amount) balance
FROM
(
SELECT * FROM @T1
) x
JOIN
(
SELECT * FROM @T1
) y
ON y.Date <= x.Date
GROUP
BY x.Date
) grp
on grp.Date = main.Date