Postgresql 中的累计和?

Cumulative Sum In Postgresql?

我有如下查询结果...

trx_id | Opening | qty_plus | qty_minus |
-------+----------+---------+-----------+
1      |  1000   |   100    |     0     |
2      |  1000   |     0    |    50     |
3      |  1000   |    10    |     0     |
4      |  1000   |    40    |     0     |
5      |  1000   |     0    |   300     |

我想要如下结果

trx_id | Opening | qty_plus | qty_minus | closing |
-------+----------+---------+-----------+---------+
1      |  1000   |   100    |     0     |   1100  |
2      |  1100   |     0    |    50     |   1050  |
3      |  1050   |    10    |     0     |   1060  |
4      |  1060   |    40    |     0     |   1100  |
5      |  1100   |     0    |   300     |    800  |

这是一个递归总数:

with recursive totals as (
  select trx_id, opening, qty_plus, qty_minus, opening + qty_plus - qty_minus as closing
  from the_table
  where trx_id = 1
  union all
  select t2.trx_id, p.closing, t2.qty_plus, t2.qty_minus, p.closing +  t2.qty_plus - t2.qty_minus
  from the_table t2
    join totals p on p.trx_id = t2.trx_id - 1
)
select * 
from totals
order by trx_id;

缺点是连接条件假定 trx_id 中没有间隙。也许 window 函数也可以做到这一点,但目前我想不出办法。

Online example