从sql中另一列的上一个值中减去一列的值

  • 本文关键字:一列 sql 上一个 sql
  • 更新时间 :
  • 英文 :


我想要一个存储减法值的列。应该在一列的值和另一列的上一个值之间进行减法运算。

以下是示例:

供应商日期2019年1月31日0:0006/20/2019 0:00[/tr>2019年8月22日0:002019年10月24日0:002020年3月26日0:00[/tr>2020年1月6日0:002020年7月27日0:00//tr>09/23/2020 0:00
客户ID 发货日期Gap
76868773 2018年10月15日0:00 12018年10月12日0:00 -4
76868773 2018年6月12日0:0021
76868773 2019年2月21日0:00 2019年4月18日0:00 7
76868773 2019年4月25日0:007
76868773 2019年6月27日0:007
76868773 2019年8月29日0:0033
76868773 2019年11月26日0:00 2020年1月21日0:00 9
76868773 2020年1月30日0:0011
76868773 2020年6月4日0:000
76868773 2020年1月6日0:002
76868773 2020年7月29日0:008

您可以使用lead()窗口函数。假设您使用的是SQL Server。

Create table and insert statements:
create table customer_shipping(Customer_ID int, Ship_date date, Supply_date date);
insert into customer_shipping values(76868773  ,'10/15/2018 0:00','12/10/2018 0:00');
insert into customer_shipping values(76868773  ,'12/06/2018 0:00','01/31/2019 0:00');
insert into customer_shipping values(76868773  ,'02/21/2019 0:00','04/18/2019 0:00');
insert into customer_shipping values(76868773  ,'04/25/2019 0:00','06/20/2019 0:00');
insert into customer_shipping values(76868773  ,'06/27/2019 0:00','08/22/2019 0:00');
insert into customer_shipping values(76868773  ,'08/29/2019 0:00','10/24/2019 0:00');
insert into customer_shipping values(76868773  ,'11/26/2019 0:00','01/21/2020 0:00');
insert into customer_shipping values(76868773  ,'01/30/2020 0:00','03/26/2020 0:00');
insert into customer_shipping values(76868773  ,'04/06/2020 0:00','06/01/2020 0:00');
insert into customer_shipping values(76868773  ,'06/01/2020 0:00','07/27/2020 0:00');
insert into customer_shipping values(76868773  ,'07/29/2020 0:00','09/23/2020 0:00');

查询:

select *, datediff(day,supply_date,lead(ship_date)over(partition by customer_id order by ship_date))gap 
from customer_shipping

输出:

客户ID768687732018-10-152018-12-10768687732018-12-06>td style="text-align:left768687732019-02-21>td style="text-align:left768687732019-04-25>td style="text-align:left768687732019-06-27td style="text-align:right;">768687732019-08-29>td style="text-align:left;">2019-10-2433768687732019-11-262020-01-21>9768687732020-01-3022020-03-2611768687732020-04-06768687732020-06-0122020-07-272768687732020-07-292020-09-23null

如果您的数据库不支持LEAD和LAG(早期版本的MS SQL不支持(,那么您可以始终使用RANK((OVER((函数为每个数据库提供一个唯一的RANK编号,然后使用1 的RANK偏移量将表连接到自身

最新更新