Calculate running total / running balance

后端 未结 6 1852
粉色の甜心
粉色の甜心 2020-11-22 10:01

I have a table:

create table Transactions(Tid int,amt int)

With 5 rows:

insert into Transactions values(1, 100)
insert into         


        
6条回答
  •  一生所求
    2020-11-22 10:33

    We're on 2008R2 and I use variables and a temp table. This also allows you to do custom things when calculating each row using a case statement (i.e. certain transactions may act differently, or you may only want a total for specific transaction types)

    DECLARE @RunningBalance int = 0
    SELECT Tid, Amt, 0 AS RunningBalance
    INTO #TxnTable
    FROM Transactions
    ORDER BY Tid
    
    UPDATE #TxnTable
    SET @RunningBalance = RunningBalance = @RunningBalance + Amt
    
    SELECT * FROM #TxnTable
    DROP TABLE #TxnTable
    

    We have a transaction table with 2.3 million rows with an item that has over 3,300 transactions, and running this type of query against that takes no time at all.

提交回复
热议问题