Subtracting one row of data from another in SQL

前端 未结 7 757
抹茶落季
抹茶落季 2020-12-09 19:06

I\'ve been stumped with some SQL where I\'ve got several rows of data, and I want to subtract a row from the previous row and have it repeat all the way down.

So her

7条回答
  •  青春惊慌失措
    2020-12-09 19:30

    Yipee!!! this does the trick:

    SELECT  f.id, f.length, 
        (f.length - ISNULL(f2.length,0)) AS diff
    FROM foo f
    LEFT OUTER JOIN foo f2
    ON  f2.id = (f.id +1)
    

    Please check for other cases also, it is working for the values you posted! Note this is for SQL Server 2005

提交回复
热议问题