【发布时间】:2021-03-02 21:25:01
【问题描述】:
我正在尝试计算每月流失率(给定月份:number_of_people_who_unsubscribed / number_of_subscribers_at_beginning_of_month)。
我有一个 subscribers 表,如下所示:
| id | start_date | end_date |
|---|---|---|
| 1 | 2020-03-17 | null |
| 2 | 2020-06-21 | 2020-09-03 |
我可以使用这样的查询计算一个月的流失率:
select
(
/* Subscriptions that ended during January */
select count(*)::decimal from subscriptions
where end_date is not null
and end_date >= '2021-01-01'
and end_date <= '2021-01-31'
) /
(
/* Subscriptions that were active at the beginning of January */
select count(*)::decimal from subscriptions
where end_date is null
or end_date >= '2021-01-01'
) as churn
这给了我一月份退订用户的单一百分比。但是,我想每个月输出这个百分比,所以我可以将它显示为折线图。我不知道从哪里开始——感觉就像我需要循环并运行每个月的查询,但感觉不对。我如何进行相同的计算,但不手动指定月份?我们可以假设每个月至少有一个 start_date 和一个 end_date,所以某种group by 可能会起作用。
最终,我正在寻找类似于以下内容的输出:
| month | churn |
|---|---|
| 2020-03 | 0.076 |
| 2020-04 | 0.081 |
| 2020-05 | 0.062 |
【问题讨论】:
标签: sql postgresql