我有一些SaaS用户数据,如下所示:
start_month end_month User_Id
2019-10 2019-10 1
2019-10 2019-11 2
2019-10 2019-12 3
2019-10 2019-12 4
2019-11 2019-11 5
2019-11 2019-12 6
2019-11 2019-12 7
2019-11 2020-01 8
2019-12 2019-12 9
2019-12 2020-01 10
2019-12 NULL 11
2019-12 2020-02 12如您所见,数据包含订阅开始日期和订阅结束日期。
start_month和end_month是从开始日期创建的字符串,格式为TO_CHAR(date_trunc('month', start_date), 'yyyy-MM') AS start_month
如果订阅仍处于活动状态,则end_month可以为空。
这是一个postgresql数据库。
使用这些数据,我需要创建一个队列报告,它应该显示每个月有多少人开始订阅,以及从该队列中有多少人在接下来的一个月结束订阅。在上面的数据中,有4个用户开始于2019-10年。1在同一个月(0)结束,1在1个月结束,2在2个月结束。类似地,我们应该得到其他开始月份队列。
很抱歉,我完全不知道如何才能得出这份报告。我已经在互联网上搜索过,但找不到任何相关的答案,因为队列只创建了开始和结束日期。请帮帮忙。
发布于 2020-08-06 18:54:24
如果我理解正确的话,您可以使用条件聚合:
select start_month, count(*),
count(*) filter (where end_month is null or to_date(end_month, 'YYYY-MM') >= to_date(start_month, 'YYYY-MM') + interval '1 month') as month_1,
count(*) filter (where end_month is null or to_date(end_month, 'YYYY-MM') >= to_date(start_month, 'YYYY-MM') + interval '2 month') as month_2
from users u
group by start_month;Here是一个db<>fiddle
https://stackoverflow.com/questions/63280398
复制相似问题