问题描述
我想创造客户留存率。
所以我有这张桌子:
id | 日期 | 购买 |
---|---|---|
1 | 2020-01 | 200 |
2 | 2020-12 | 100 |
2 | 2020-03 | 150 |
3 | 2020-03 | 200 |
1 | 2020-07 | 120 |
1 | 2020-08 | 300 |
3 | 2020-05 | 250 |
我想要这个输出:
购买月份 | 第一个购买月 | 总计 |
---|---|---|
0 | 2020-01 | 200 |
6 | 2020-01 | 320 |
7 | 2020-01 | 620 |
0 | 2020-03 | 350 |
4 | 2020-03 | 600 |
11 | 2020-03 | 700 |
“在 2020 年 1 月下第一笔订单的客户在第 0 个月(2020 年 1 月)花费了 200,在第 6 个月(2020 年 7 月)花费了 120 (320-200)。”
“在 2020 年 3 月下第一笔订单的客户在第 0 个月(即 2020 年 3 月)花费了 350,在第 4 个月(即 2020 年 5 月)花费了 250 (600-350)。”
提前感谢您的帮助
解决方法
您可以使用窗口函数和公共表表达式轻松完成。
架构和插入语句:
create table purchases(id int,date date,purchase int);
insert into purchases values(1,'2020-01',200);
insert into purchases values(2,'2020-12',100);
insert into purchases values(2,'2020-03',150);
insert into purchases values(3,200);
insert into purchases values(1,'2020-07',120);
insert into purchases values(1,'2020-08',300);
insert into purchases values(3,'2020-05',250);
查询:
with cte as
(
select id,date,purchase,min(date)over(partition by id) FirstPurchaseMonth from purchases
),cte2 as
(
select substr(date,6,2)-substr(firstpurchasemonth,2) Purchasemonth,max(FirstPurchaseMonth)firstpurchasemonth,sum(purchase)total from cte
group by firstpurchasemonth,substr(date,2)
)
select purchasemonth,firstpurchasemonth,sum(total)over(partition by firstpurchasemonth order by purchasemonth)total
from cte2
输出:
购买月 | firstpurchasemonth | 总计 |
---|---|---|
0 | 2020-01 | 200 |
6 | 2020-01 | 320 |
7 | 2020-01 | 620 |
0 | 2020-03 | 350 |
2 | 2020-03 | 600 |
9 | 2020-03 | 700 |
db