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

前端 未结 4 1626
闹比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条回答
  •  猫巷女王i
    2020-12-18 00:22

    Here is an example using ROW_NUMBER() if the Id's aren't necessarily in order:

    ;with DataRaw as (
        select 1 as Id, '01/01/11' as Date, 5 as Column1 union
        select 2 as Id, '02/01/11' as Date, 2 as Column1 union
        select 4 as Id, '03/01/11' as Date, 3 as Column1
    ),
    Data as (
        select RowId = ROW_NUMBER() over (order by Id), Id, Date, Column1 from DataRaw
    ),
    Data2 as (
        select
            RowId, id, Date, Column1, Column1 as Column2
        from
            Data d
        where
            RowId = 1
    
        union all
    
        select
            d1.RowId, d1.id, d1.Date, d1.Column1, (1+d1.column1)*(1+d2.column2) as column2
        from
            Data d1
        cross join
            Data2 d2
        where
            d2.RowId + 1 = d1.RowId
    )
    select
        Id, Date, Column1, Column2
    from
        Data2
    

提交回复
热议问题