计算运行总量/运行余额我有张桌子:create table Transactions(Tid int,amt int)5行:insert into Transactions values(1, 100)insert into Transactions values(2, -50)insert into Transactions values(3, 100)insert into Transactions values(4, -100)insert into Transactions values(5, 200)期望产出:TID amt balance--- ----- -------1 100 1002 -50 503 100 1504 -100 505 200 250基本上,对于第一次记录,余额将是相同的amt,第二个余额将是先前余额+当前余额的加法。amt..我正在寻找一种最佳的方法。我可以考虑使用函数或相关子查询,但不确定具体如何实现。
3 回答
慕标5832272
TA贡献1966条经验 获得超4个赞
select *, sum(amt) over (order by Tid) as running_total from Transactions
select *,(select sum(amt) from Transactions where Tid<=t.Tid) as running_total from Transactions as t
冉冉说
TA贡献1877条经验 获得超1个赞
DECLARE @RunningBalance int = 0SELECT Tid, Amt, 0 AS RunningBalanceINTO #TxnTableFROM TransactionsORDER BY TidUPDATE #TxnTableSET @RunningBalance = RunningBalance = @RunningBalance + AmtSELECT * FROM #TxnTableDROP TABLE #TxnTable
添加回答
举报
0/150
提交
取消