Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在sql中根据第一个月的采购组保留价值并计算下一次采购金额_Sql_Database_Sqlite_Retention - Fatal编程技术网

如何在sql中根据第一个月的采购组保留价值并计算下一次采购金额

如何在sql中根据第一个月的采购组保留价值并计算下一次采购金额,sql,database,sqlite,retention,Sql,Database,Sqlite,Retention,我想创建客户保留 所以我有一张桌子: 身份证件 日期 购买 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 您可以使用窗口函数和通用表表达式轻松完成此操作 架构和插入语句: create table purchases(id int, date date, purchase int); insert into purchases v

我想创建客户保留

所以我有一张桌子:

身份证件 日期 购买 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
您可以使用窗口函数和通用表表达式轻松完成此操作

架构和插入语句:

 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 
 
输出:

采购月 第一个月 全部的 0 2020-01 200 6. 2020-01 320 7. 2020-01 620 0 2020-03 350 2. 2020-03 600 9 2020-03 700
请记住,选择标记时,
jQuery
Query
是不同的