The heading of this question is probably poorly worded as I am finding it difficult to explain concisely what I want, other than to provide some demo data.
I have a query which returns the following data from a sql table:
ID Job User Amount
1 101 Bob 100
2 101 Pete 500
3 102 Bob 400
4 102 Pete 200
5 101 Pete 850
6 102 Bob 650
What I want is the query to also return an additional field called (Difference), which contains the difference between the Amount in consecutive entries for the same User and Job. Hence the data I would like returned would be as follows:
ID Job User Amount Diff
1 101 Bob 100 100
2 101 Pete 500 500
3 102 Bob 400 400
4 102 Pete 200 200
5 101 Pete 850 350
6 102 Bob 650 250
In the first four rows, the Diff is the same as the Amount because each is the first entry per User per Job (hence the Difference is calculated with reference to a starting Amount of nil in effect).
The last two lines contain information for a User and Job combination that have appeared in the table previously, and hence Diff is calculated as follows:
Job 101 User Pete 850 - 500 = 350
Job 102 User Bob 650 - 400 = 250
I’ve never had to compare data from rows like this in a SQL query before so don’t really know where to start. Any help would be much appreciated.
Added
Please note the Amount is not a running total. It is a subjective assessment made periodically of the value of a User’s input in each particular job. It is possible that the Amount could in fact go down from one assessment to the next. What I want is a query that returns the difference between successive assessments ‘Amounts’.
Alternative Explanation
I’m looking to return a history trail of movements in the Amount assessed. So another example, looking at a single Job and User is as follows:
Job User Amount Movement
101 Bob 100 100
101 Bob 500 400
101 Bob 400 (100)
101 Bob 1,000 600
However, as per the original example, this information will need to be extracted from a table which contains many Jobs and Users all intermingled.
For SQL Server 2012, try this
This assumes that ID=5 value is wrong in your example
For “previous value” per pair
For “first value” per pair