【问题标题】:Calculating monthly churn计算月流失率
【发布时间】: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


    【解决方案1】:

    使用您的数据逻辑和月份序列:

    select to_char(running_month, 'yyyy-mm') as "month",
    (
      /* Subscriptions that ended during January */
      select count(*)::numeric from subscriptions
      where end_date is not null
      and end_date >= running_month
      and end_date <= running_month + interval '1 month - 1 day'
    ) /
    (
      /* Subscriptions that were active at the beginning of January */
      select count(*)::numeric from listings
      where end_date is null
      or end_date >= running_month
    ) as churn
    from generate_series ('2020-01-01'::date, '2020-12-01'::date, interval '1 month') as running_month;
    

    【讨论】:

    • 太棒了,这很有效,而且很容易理解。谢谢!
    猜你喜欢
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多