sql - 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”相同
非常感谢
解决方案
推荐阅读
- python - Tkinter 回调 Traceback 中的异常(最近一次调用最后一次):在 __call__ 返回 self.func(*args) 第 1646 行,在配置中
- python - 熊猫数据帧乘法
- javascript - React Hook Form - 智能组件 - 当输入包装在元素中时表单损坏
- cmake - CMake 相对路径库通信
- python - 如何在python中创建自定义数字列表
- matlab - 如何在 MATLAB 中使用 GPML 工具箱创建加权复合协方差函数?
- reactjs - Next Auth:成功登录前重定向页面
- docker-compose - 具有不同环境变量的多个作业 - Circle CI Docker.compose.yml (JAVA- Maven Project)
- javascript - mongodb full $text search在排序和过滤时返回重复项
- python - int16 和 int64 的区别