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
To reset a Windowed Aggregate based on a condition you need to add another level to define the different groups of rows:
with cte as
(
select itemorder, name, qty,
case -- start qty for each group
when itemorder = max(itemorder) over () then 100 -- newest row
when name = 'X' then qty
else 0
end
-- only sum 'A' rows
+ case when name = 'A' then qty else 0 end as new_qty,
-- grp value increases only when name = 'X'
-- this assigns the same value to each row in a group
-- will be used in the next step to PARTITION BY
sum(case when name = 'X' then 1 else 0 end)
over (order by itemorder desc
rows unbounded preceding) as grp
from myTable
)
select itemorder, name, qty,
sum(new_qty)
over (partition by grp
order by itemorder desc
rows unbounded preceding ) as modified_sum
from cte
order by item order
See fiddle