I have asked a similar question previously, but posting a new one as I do not want to confuse other
members, and there is an additional column.
What I am looking for is to update the column ItemActual. This needs to be updated with the difference with ItemValue for the latest CurrentTime for the same StartTime if any.
If there is no other entry for the same StartTime other than the current row, it needs to be the ItemValue itself. The comparisons are only to be done for items with the same name.
For eg, Rownum 283, ItemActual = 347013 (since there is no other row with same StartTime).
This applies to row 235 as well, i.e. ItemActual = 1086054.00
For row 190, this needs to be 664031.00 - 533023.00 (comparing with row 145) = 131008
But for row 10, this will be 532023.00, since there is no earlier entry of same item with same StartTime.
Rownum Name ItemValue CurrentTime StartTime
283 ABC 347013.00 3/05/2012 16:01 29/04/2012 6:29
235 ABC 1086054.00 26/03/2012 14:05 7/03/2012 21:18
190 ABC 664031.00 13/02/2012 13:42 29/01/2012 6:39
145 ABC 533023.00 7/02/2012 14:01 29/01/2012 6:39
100 ABC 532023.00 7/02/2012 13:33 29/01/2012 6:39
55 ABC 532023.00 7/02/2012 12:52 29/01/2012 6:39
10 ABC 532023.00 7/02/2012 12:51 29/01/2012 6:39
310 DEF 351012.00 3/05/2012 16:01 29/04/2012 6:29
261 DEF 1339066.00 26/03/2012 14:05 7/03/2012 21:18
215 DEF 785034.00 13/02/2012 13:42 29/01/2012 6:39
170 DEF 620026.00 7/02/2012 14:01 29/01/2012 6:39
You can try something like this:
I get an output something like this:
The solution basically does this:
it creates a CTE (Common Table Expression) and “partitions” your data by
Name,StartTimeand orders these rows byCurrentTime DESC– so the most recent entry for eachName,StartTimegroup will get an RX (Row indeX) of 1it then joins that CTE against itself, shifted by one RX – so I’m comparing RX = 1 to RX = 2 (if present) etc.
if a “shifted” row is present, the difference in the
ItemValuevalues is returned asItemActual– otherwise theItemValuefrom the main row is returnedI hope this solves your problem