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

前端 未结 4 1622
闹比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条回答
  •  Happy的楠姐
    2020-12-18 00:21

    edit: shoudld have read the question better...

    Another go woudl be this:

    ;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 Ord = ROW_NUMBER() over (order by Id), Id, Date, Column1 from DataRaw
    ),
    select -- formula goes here, using current and prev as datasources.
    from  data current
          left join data prev on current.Ord = prev.Ord + 1  -- pick the previous row by adding 1 to the ordinal
    

    I think a normal join to get to the previous row would be faster than a CTE. You;d have to check for yourself though.

    Looks easier to me.

    Good luck, GJ

提交回复
热议问题