I'm using Postgresql 9.2 and I need to sum quantitys from buttom up with initial value of 100, however if I encounter a row with name X i need to restart the SUM from the value of qty in this row.
for example:
itemorder name qty
1 A -20
2 A2 350
3 X 40
4 A 50
5 A -10
6 A2 10
Should generate:
itemorder name qty modifyed_sum
1 A -20 20 / 40 + (-20)
2 A2 350 40 / not A
3 X 40 40 / encounter X, restart sum with X qty.
4 A 50 140 / 90 + 50
5 A -10 90 / 100 + (-10)
6 A2 10 100 / not A
I used this query to do the Sum:
SELECT 100 + Sum(CASE WHEN name = 'a' THEN qty ELSE 0 END)OVER(ORDER BY itemorder DESC) as modifyed_sum,
qty,
name,
itemorder
FROM Table_Name
ORDER BY itemorder ASC
How can I modify it to handel the X case? (There can be more than one X)