How to SUM() over column with reset condition?

后端 未结 2 533
逝去的感伤
逝去的感伤 2021-01-03 16:05

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

2条回答
  •  迷失自我
    2021-01-03 16:42

    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

提交回复
热议问题