SQL 按时间条件分组的累计和

SQL Cumulative Sum by Group by time condition

我有一个 table 列 dummy_id, date_registered, item_id数量价格,像这样:

dummy_id date_registered item_id quantity price my_cumulative
1 2013-07-01 100 10 34.5 10
2 2013-07-01 145 8 2.3 8
3 2013-07-11 100 20 34.5 30
4 2013-07-23 100 15 34.5 45
5 2013-07-24 145 10 34.5 18

如果我想计算列 my_cumulative,其中包含 date_registered 每个 item_id 订单的累计总数,我使用此代码:

select dummy_id, date_registered, item_id, quantity, price,
       sum(quantity) over (partition by item_id order by date_registered) as cumulative
from table t;

而且效果很好。但是,如果我现在想在每一行的 my_cumulative 列中只计算上个月的订单怎么办? (仅计算date_register列小于当前行的数量之和,不超过一个月)

在 sql 中有什么方法可以做到这一点吗? (更喜欢 postgresql)

如果您想要当月的累计数量——我怀疑您想要的是,请更改 partition by:

select dummy_id, date_registered, item_id, quantity, price,
       sum(quantity) over (partition by item_id, date_trunc('month', date_registered) order by date_registered) as cumulative
from table t;

如果你真的想要上个月,那么使用范围 window 帧,间隔为:

select dummy_id, date_registered, item_id, quantity, price,
       sum(quantity) over (partition by item_id
                           order by date_registered
                           range between interval '1 month' preceding and current row
                          ) as cumulative
from table t;

第一个对我来说似乎更有用。