[英]Postgres cumulative count over time
I'm trying to find the number of active subscriptions in a month over a timescale. 我试图在一个月内找到一个月内活跃订阅的数量。
Table: Subscriptions Fields: 表:订阅字段:
A subscription is considered active at a particular timestamp when: 在以下情况下,订阅在特定时间戳中被视为活动:
Example: 例:
This is what I tried: 这是我试过的:
select "Month", sum(sub) over (order by "Month" asc) as "Active subscriptions"
from
(select to_char(subscriptions."creationDate" at time zone '-7', 'YYYY-MM') as "Month",
count(distinct subscriptions.id) as sub
from subscriptions
where (to_char(subscriptions."deletionDate" at time zone '-7', 'YYYY-MM') is null
or to_char(subscriptions."deletionDate" at time zone '-7', 'YYYY-MM') >= to_char(subscriptions."creationDate" at time zone '-7', 'YYYY-MM') )
group by "Month") as foo
However, the issue with this is that it is including the count of non-active subscriptions in the previous month. 但是,问题在于它包含了上个月的非活动订阅数。 To illustrate what I mean, my query above seems to include Subscription B (in example above) as an active subscription in July 2014.
为了说明我的意思,我的上述查询似乎包括2014年7月的订阅B(在上面的示例中)作为有效订阅。
I'm not sure how to get my "Active subscriptions" for a particular month to remove the count of subscriptions that are no longer active in the previous months. 我不确定如何获取特定月份的“有效订阅”以删除前几个月不再有效的订阅数。
Thank you! 谢谢! :)
:)
SELECT m, count(subscriptions.*)
FROM subscriptions
JOIN generate_series('2010-01-01'::date, now(), interval '1 mon') AS m
ON m >= subscriptions.creationDate AND
(subscriptions.deletionDate IS NULL OR m <= subscriptions.deletionDate)
/* You may get better indexed performance if you use a date
far in the future for current
accounts, instead of NULL. Then you can use BETWEEN */
GROUP BY m ORDER BY m;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.