I have a table that I want to find for each row id the amount remaining from the total. However, the order of amounts is in an ascending order.
id amount
1 3
2 2
3 1
4 5
The results should look like this:
id remainder
1 10
2 8
3 5
4 0
Any thoughts on how to accomplish this? I’m guessing that the over clause is the way to go, but I can’t quite piece it together.Thanks.
SQL Server 2008 answer, I can’t provide an SQL Fiddle, it seems it strips the
beginkeyword, resulting to syntax errors. I tested this on my machine though:To achieve your desired output:
Rationale for guarded running total: http://www.ienablemuch.com/2012/05/recursive-cte-is-evil-and-cursor-is.html
Choose the lesser evil 😉