首页 > 解决方案 > SQL 中的累积保留率

问题描述

我已经设法使用 PostgresSQL 从销售数据中按月和同类群组计算保留率,但我遇到了“累积保留率”问题。

下面是一个样本集。2017 年 1 月队列中有 3 位客户,因为他们的第一次购买是在 2017 年 1 月。同样在那个月内,客户“3”回来了。2017 年 2 月,即 1 个月_从_队列_月,客户“1”回来了。2017 年 3 月,也就是 2 个月_从_队列_月,客户“2”回来了。2017 年 4 月,也就是 3 个月_从_队列_月,有两个客户回来了,“2”和“1”。

WITH sale_data AS (
SELECT
'2017-01-01' AS order_date,
'1' AS customer_id
UNION
SELECT
'2017-01-03' AS order_date,
'2' AS customer_id
UNION
SELECT
'2017-01-04' AS order_date,
'3' AS customer_id
UNION
SELECT
'2017-01-05' AS order_date,
'3' AS customer_id
UNION
SELECT
'2017-02-01' AS order_date,
'1' AS customer_id
UNION
SELECT
'2017-03-01' AS order_date,
'2' AS customer_id
UNION
SELECT
'2017-04-01' AS order_date,
'1' AS customer_id
UNION
SELECT
'2017-04-02' AS order_date,
'2' AS customer_id
)

我已经做到了

_____________month_since_cohort_month____0______1_______2_______3
cohort_month_____________________________________________________
2017-01__________________________________3______1_______1_______2

这只是每个月内回来的客户数量_diff

我被什么困住了

我需要计算每个月到目前为止回来的客户数量,这意味着上个月回来的所有客户也都被计算在内。下面是预期的结果

_____________month_since_cohort_month____0______1_______2_______3
cohort_month_____________________________________________________
2017-01__________________________________3______2_______3_______3

对于month_since_cohort_month“1”,有两个客户在该点之前回来,对于month_since_cohort_month“2”,有三个客户在该点之前回来与month_since_cohort_month“3”相同

非常感谢

标签: sqlpostgresql

解决方案


推荐阅读