Calculate running total / running balance

后端 未结 6 1730
粉色の甜心
粉色の甜心 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:40

    In SQL Server 2008+

    SELECT  T1.* ,
            T2.RunningSum
    FROM    dbo.Transactions As T1
            CROSS APPLY ( SELECT    SUM(amt) AS RunningSum
                          FROM      dbo.Transactions AS CAT1
                          WHERE     ( CAT1.TId <= T1.TId )
                        ) AS T2
    

    In SQL server 2012+

    SELECT  * ,
            SUM(T1.amt) OVER ( ORDER BY T1.TId 
                            ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS RunningTotal
    FROM    dbo.Transactions AS t1
    

提交回复
热议问题