Soldato
- Joined
- 16 Nov 2003
- Posts
- 9,682
- Location
- On the pale blue dot
Hi guys, I have a bit of a puzzle I'm getting nowhere with. Consider the following table:
What I need to do is turn this data into the form that for each id, I have the difference in value between one row and the next smallest audit key, see below with additional explanation:
So in theory what I want to do is select the entire table, order it by id and then audit key (descending) and then join it to the same table shifted down one (ish, the last row for each id would end up being ignored).
Any ideas? This is in SQL Server 2005 if it helps, so I don't have access to unique functions like MySQL's LIMIT.
Code:
id | value | auditkey
---------------------------------
1 | 10 | 5
1 | 8 | 3
1 | 4 | 2
2 | 20 | 5
2 | 4 | 4
What I need to do is turn this data into the form that for each id, I have the difference in value between one row and the next smallest audit key, see below with additional explanation:
Code:
id | diff
----------------
1 | 2 (Auditkey 5->3: 10 - 8 = 2
1 | 4 (Auditkey 3->2: 8 - 4 = 4
2 | 16 (Auditkey 5->4: 20 - 4 = 16
So in theory what I want to do is select the entire table, order it by id and then audit key (descending) and then join it to the same table shifted down one (ish, the last row for each id would end up being ignored).
Any ideas? This is in SQL Server 2005 if it helps, so I don't have access to unique functions like MySQL's LIMIT.