如何解决如何在sql中根据第一个月购买的组保留价值和计算下一个购买量
我想创造客户留存率。
所以我有这张桌子:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。