如何在 BigQuery SQL 中计算完整/重复保留

问题描述

我正在尝试计算“滚动留存率”或“重复留存率”(不确定这是什么合适的名称),但是我只想计算每个月下订单的用户比例的情况连续。

因此,如果 10 位用户在 2020 年 1 月下订单,其中 5 位用户在 2 月返回,那么这相当于 50% 的留存率。

现在对于 3 月份,我只想考虑 2 月份订购的 5 位用户,但仍需注意 1 月份的总队列规模。

因此,如果 2 月份的 2 位用户在 3 月份返回,则 3 月份的留存率为 2/10 = 20%。如果Jan用户在2月份没有回来,在3月份下订单,他们不会被计算在3月份的计算中,因为他们在2月份没有回来。

基本上,这种留存率会逐渐降低到 0%,并且永远不会增加

这是我目前所做的:

 WITH first_order AS (SELECT 
  customerEmail,MIN(orderedat) as firstOrder,FROM fact AS fact
GROUP BY 1 ),cohort_data AS (SELECT 
  first_order.customerEmail,orderedAt as order_month,MIN(FORMAT_DATE("%y-%m (%b)",date(firstorder))) as cohort_month,FROM first_order as first_order
LEFT JOIN fact as fact
ON first_order.customeremail = fact.customeremail
GROUP BY 1,2,FACT.orderedAt),cohort_count AS (select cohort_month,count(distinct customeremail) AS total_cohort_count FROM cohort_data GROUP BY 1 )

SELECT  
    cd.cohort_month,date_trunc(date(cd.order_month),month) as order_month,total_cohort_count,count(distinct cd.customeremail) as total_repeat
FROM cohort_data as cd
JOIN cohort_data as last_month
    ON cd.customeremail= last_month.customeremail
    and date(cd.order_month) = date_add(date(last_month.order_month),interval 1 month)
LEFT JOIN cohort_count AS cc 
    on cd.cohort_month = cc.cohort_month
GROUP BY 1,3
ORDER BY  cohort_month,order_month ASC

这是结果。我不确定我哪里出错了,但数字太小了,而且留存率在几个月内增加了,这是不应该的。

enter image description here

我在上一个查询中执行了 INNER JOIN,因此我可以将上个月与当前月份进行比较,但它并没有完全按照我想要的方式工作。

样本数据:

enter image description here

感谢您的帮助

解决方法

我会从每个客户每月一行开始。然后,我会枚举客户/月并只保留那些没有间隙的。 . .并汇总:

with customer_months as (
      select customer_email,date_trunc(ordered_at,month) as yyyymm,min(date_trunc(ordered_at,month)) over (partition by customer_email) as first_yyyymm
      from cohort_data
      group by 1,2 
     )
select first_yyyymm,yyyymm,count(*)
from (select cm.*,row_number() over (partition by custoemr_email order by yyyymm) as seqnum
      from customer_months cm
     ) cm
where yyyymm = date_add(first_yyyymm,interval seqnum - 1 month)
group by 1,2
order by 1,2;