Calculating value using previous value of a row in T-SQL

前端 未结 4 1620
闹比i
闹比i 2020-12-18 00:19

I got following table and want to calculate value of Column2 on each row using the value of the same column (Column2) from the previous row in a sql without using cursor or

4条回答
  •  一整个雨季
    2020-12-18 00:20

    Assuming at least SQL Server 2005 for the recursive CTE:

    ;with cteCalculation as (
        select t.Id, t.Date, t.Column1, t.Column1 as Column2
            from YourTable t
            where t.Id = 1
        union all
        select t.Id, t.Date, t.Column1, (1+t.Column1)*(1+c.Column2) as Column2
            from YourTable t
                inner join cteCalculation c
                    on t.Id-1 = c.id
    )
    select c.Id, c.Date, c.Column1, c.Column2
        from cteCalculation c
    

提交回复
热议问题