我正在尝试在一个时间段内找到一个月内有效订阅的数量。
表:订阅 字段:
在以下情况下,订阅被视为在特定时间戳有效:
示例:
这就是我的尝试:
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
然而,问题在于它包括上个月的非活跃订阅数。为了说明我的意思,我的上述查询似乎包括2014年7月的订阅B(上例中)作为有效订阅。
我不确定如何获取特定月份的“有效订阅”,以删除过去几个月内不再有效的订阅数。
谢谢! :)
答案 0 :(得分:5)
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;