【发布时间】:2021-08-14 05:29:35
【问题描述】:
我很难创建包含每月持续订阅总和的统计数据
我有表订阅
id | created_at | cancelled_at
----------------------------------------
1 | 2020-12-29 13:56:12 | null
2 | 2021-02-15 01:06:25 | 2021-04-21 19:35:31
3 | 2021-03-22 02:42:19 | null
4 | 2021-04-21 19:35:31 | null
统计数据应如下所示:
month | count
---------------
12/2020 | 1 -- #1
01/2021 | 1 -- #1
02/2021 | 2 -- #1 + #2
03/2021 | 3 -- #1 + #2 + #3
04/2021 | 3 -- #1 + #3 + #4, not #2 since it ends that month
05/2021 | 3 -- #1 + #3 + #4
到目前为止,我能够列出我需要以下统计数据的所有月份:
select generate_series(min, max, '1 month') as "month"
from (
select date_trunc('month', min(created_at)) as min,
now() as max
from subscriptions
) months;
并获得特定月份的正确订阅数量
select sum(
case
when
make_date(2021, 04, 1) >= date_trunc('month', created_at)
and make_date(2021, 04, 1); < date_trunc('month', coalesce(cancelled_at, now() + interval '1 month'))
then 1
else 0
end
) as total
from subscriptions
-- returns 3
但我正在努力将它们结合在一起......OVER(我没有经验)对我有用吗?我找到了Count cumulative total in Postgresql,但情况不同(日期是固定的)......还是以某种方式使用FOR 的函数的正确方法?
【问题讨论】:
标签: sql postgresql aggregate-functions