I have a TSQL table in which the data is the following:
ID Value
3252 2
93528 3
2351 5
1424 19
How can I create an additional column which contains the previous value for a given row? I cannot use the LAG()
function as I am using SQL Server 2008.
Example:
ID Value PreviousValue
3252 2 NULL
93528 3 2
2351 5 3
1424 19 5
I am stuck here as the ID of each row is non-sequential. I believe I have to order the rows somehow, and have made an attempt with the following:
SELECT RANK() OVER (ORDER BY Value) as Rank, ID, Value, PreviousValue
FROM MyTable t1
JOIN MyTable t2 ON t1.id = t2.id
ORDER BY Value;
Result:
Rank ID Value PreviousValue
1 3252 2 2
2 93528 3 3
3 2351 5 5
4 1424 19 9