【问题标题】:Cumulative Sum In Postgresql?Postgresql中的累积和?
【发布时间】:2020-01-28 10:35:25
【问题描述】:

我有如下查询结果...

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  |

【问题讨论】:

  • 除非存在另一列(未显示)维护交易的顺序,否则无法回答此问题。有这样的专栏吗?
  • @TimBiegeleisen 请再次检查问题。
  • 与您的问题无关,但 Postgres 9.2 是 no longer supported,您应该尽快计划升级。

标签: postgresql-9.2


【解决方案1】:

这是一个递归总计:

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 中没有间隙的连接条件。也许这对窗口函数也是可能的,但目前我想不出办法。

Online example

【讨论】:

  • #a_horse_with_no_name - 非常感谢...运行良好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
  • 2017-09-16
  • 2021-03-13
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多