【问题标题】:SQL Cumulative Sum by Group by time conditionSQL Cumulative Sum by Group by time 条件
【发布时间】:2021-06-13 17:24:41
【问题描述】:

我有一张表格,其中包含 dummy_id、date_registered、item_id、quantity、price,像这样:

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)

【问题讨论】:

  • 请定义“上个月”的含义。不清楚。
  • 对于 item_id=100 和 date_registered=2013-07-23 的行,my_cumulative 列包含自 2013-06-23 以来的订单总数,而不是从表的开头开始跨度>

标签: sql postgresql window-functions cumulative-sum


【解决方案1】:

如果你想要当月的累计数量——我怀疑你想要的,然后更改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;

如果你真的想要最后一个月,那么使用带间隔的范围窗口框架:

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;

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

【讨论】:

  • 感谢您的回答,但这并不是我所需要的。在您的解决方案中,时间间隔由日历月指定,并且彼此不重叠。但我需要每一行包含过去 30 天相对于它的总量。即日期为2013-07-23的行包含从2013-06-23开始的总量,日期为2013-07-11的行包含从2013-06-11开始的总量
  • sql中有这种可能吗?
  • @ilyazyulyaev 。 . .试试第二个。我不小心把date_trunc() 留在了partition by 中。我删除了它。
猜你喜欢
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
  • 2021-01-24
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多