How to get difference between two rows for a column field?

SELECT
   [current].rowInt,
   [current].Value,
   ISNULL([next].Value, 0) - [current].Value
FROM
   sourceTable       AS [current]
LEFT JOIN
   sourceTable       AS [next]
      ON [next].rowInt = (SELECT MIN(rowInt) FROM sourceTable WHERE rowInt > [current].rowInt)

EDIT:

Thinking about it, using a subquery in the select (ala Quassnoi’s answer) may be more efficient. I would trial different versions, and look at the execution plans to see which would perform best on the size of data set that you have…

EDIT2:

I still see this garnering votes, though it’s unlikely many people still use SQL Server 2005.

If you have access to Windowed Functions such as LEAD(), then use that instead…

SELECT
  RowInt,
  Value,
  LEAD(Value, 1, 0) OVER (ORDER BY RowInt) - Value
FROM
  sourceTable

Leave a Comment