sql如何根据第一个月的购买组保值计算下一次的购买量

How to retain value and compute based on group of first month purchase the next amount of purchase in sql

我想留住客户。

所以我有这个 table :

id date purchase
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

我想要这个输出:

purchase month first purchase month total
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)。”

预先感谢您的帮助

您可以使用 window 函数和常用的 table 表达式轻松完成。

架构和插入语句:

 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,    '2020-03',  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,6,2) Purchasemonth, max(FirstPurchaseMonth)firstpurchasemonth, 
       purchase,sum(purchase)total from cte
       group by firstpurchasemonth,substr(date,6,2)-substr(firstpurchasemonth,6,2) 
     )
     select purchasemonth,firstpurchasemonth,sum(total)over(partition by firstpurchasemonth order by purchasemonth)total
     from cte2 
 

输出:

Purchasemonth firstpurchasemonth total
0 2020-01 200
6 2020-01 320
7 2020-01 620
0 2020-03 350
2 2020-03 600
9 2020-03 700

dbhere