You can do this with the ROW_NUMBER() function:
;with cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY AccountNumber ORDER BY ValueDate) AS RN FROM YourTable) SELECT a.*,a.Amount - b.Amount AS Diff FROM cte a LEFT JOIN cte b ON a.AccountNumber = b.AccountNumber AND a.RN = b.RN -1
The ROW_NUMBER() function assigns a number to each row. PARTITION BY is optional, but is used to start numbering for each value in the group, that is: if you are PARTITION BY AccountNumber , for each unique value of AccountNumber numbering starts at 1. ORDER BY , of course, is used to determine how numbering should be performed , and is required in the function ROW_NUMBER() .
Used in cte, which you can combine by yourself using ROW_NUMBER() to shift the join by 1 record, allowing comparisons between lines.
In SQL Server 2012, the LEAD() and LAG() functions simplify comparisons between rows.
source share