繁体   English   中英

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

[英]How to Calculate Full/Repeat Retention in BigQuery SQL

我正在尝试计算“滚动保留”或“重复保留”(不确定此名称的适当名称),但我只想计算每个月连续下订单的用户比例。

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

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

因此,如果 2 月的 2 位用户在 3 月回来,则 3 月的留存率为 2/10 = 20%。 如果 1 月的用户在 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,2,3
ORDER BY  cohort_month, order_month ASC

这是结果。 我不确定我在哪里弄错了,但是数字太小了,并且保留在某些月份会增加,这是不应该的。

在此处输入图像描述

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

样本数据:

在此处输入图像描述

我会很感激任何帮助

我会从每个客户每月一排开始。 然后,我会列举客户/月份,只保留那些没有差距的。 . . 和聚合:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM