76868773 2018-10-15 2018-12-10 76868773 2018-12-06 >td style="text-align:left76868773 2019-02-21 >td style="text-align:left76868773 2019-04-25 >td style="text-align:left76868773 2019-06-27 td style="text-align:right;">768687732019-08-29 >td style="text-align:left;">2019-10-2433 76868773 2019-11-26 2020-01-21 >976868773 2020-01-30 22020-03-26 11 76868773 2020-04-06 76868773 2020-06-01 22020-07-27 2 76868773 2020-07-29 2020-09-23 null
我想要一个存储减法值的列。应该在一列的值和另一列的上一个值之间进行减法运算。
以下是示例:
客户ID | 发货日期 | 供应商日期Gap | ||
---|---|---|---|---|
76868773 | 2018年10月15日0:00 | 12018年10月12日0:00 | -4 | |
76868773 | 2018年6月12日0:00 | 2019年1月31日0:0021 | ||
76868773 | 2019年2月21日0:00 | 2019年4月18日0:00 | 7 | |
76868773 | 2019年4月25日0:00 | 06/20/2019 0:007 | [/tr>||
76868773 | 2019年6月27日0:00 | 2019年8月22日0:007 | ||
76868773 | 2019年8月29日0:00 | 2019年10月24日0:0033 | ||
76868773 | 2019年11月26日0:00 | 2020年1月21日0:00 | 9 | |
76868773 | 2020年1月30日0:00 | 2020年3月26日0:0011 | [/tr>||
76868773 | 2020年6月4日0:00 | 2020年1月6日0:000 | ||
76868773 | 2020年1月6日0:00 | 2020年7月27日0:002 | //tr>||
76868773 | 2020年7月29日0:00 | 09/23/2020 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
输出:
客户ID如果您的数据库不支持LEAD和LAG(早期版本的MS SQL不支持(,那么您可以始终使用RANK((OVER((函数为每个数据库提供一个唯一的RANK编号,然后使用1 的RANK偏移量将表连接到自身