Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Calculando o valor usando o valor anterior de uma linha no T-SQL


Assumindo pelo menos o SQL Server 2005 para o CTE recursivo:
;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