简体   繁体   中英

How to compare current row with previous column next row in sql

Date from    Date to    
2018-12-11  2019-01-08   
2019-01-08  2019-02-09  
2019-02-10  2019-03-14  
2019-03-17  2019-04-11   
2019-04-15  2019-05-16  
2019-05-16  2019-06-13  

output will be like this

Date from     Date to     Days
2018-12-11   2019-01-08   0 
2019-01-08   2019-02-09   1
2019-02-10   2019-03-14   3
2019-03-17   2019-04-11   4 
2019-04-15   2019-05-16   0
2019-05-16   2019-06-13   -

You want lead() and a date diff function:

select 
    date_from,
    date_to,
    datediff(day, date_to, lead(date_from) over(order by date_from)) days
from mytable

datediff() is a SQLServer function. There are equivalents in other RDBMS.

Side note: I would recommend againts using a string value ( - ) for records that do not have a next record, since other values are numeric (the datatypes in a column must be consistant). null is good enough for this (which the above query will produce).

Demo on DB Fiddle :

date_from           | date_to             | days
:------------------ | :------------------ | ---:
11/12/2018 00:00:00 | 08/01/2019 00:00:00 |    0
08/01/2019 00:00:00 | 09/02/2019 00:00:00 |    1
10/02/2019 00:00:00 | 14/03/2019 00:00:00 |    3
17/03/2019 00:00:00 | 11/04/2019 00:00:00 |    4
15/04/2019 00:00:00 | 16/05/2019 00:00:00 |    0
16/05/2019 00:00:00 | 13/06/2019 00:00:00 | null

To return the difference between two date values in days you could use the DATEDIFF() Function, something like:

SELECT DATEDIFF(DAY, DayFrom, DayTo) AS 'DaysBetween'
FROM DateTable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM