简体   繁体   中英

SQL: find difference between dates

I have searched google and stack overflow community but did not get the result i am looking for

My table - which has employee start_date and end_date of employee's shift

id    start_date   end_date
-----------------------------
 1    2019-01-05   2019-01-11
 1    2019-01-15   2019-01-18
 1    2019-01-25   2019-01-31
 2    2019-01-13   2019-01-17
 2    2019-01-21   2019-01-28

Expected Output

id    start_date   end_date     total_days_diff
------------------------------------------------
 1    2019-01-05   2019-01-11        4
 1    2019-01-15   2019-01-18        7
 1    2019-01-25   2019-01-31        NA
 2    2019-01-13   2019-01-17        4
 2    2019-01-21   2019-01-28        NA

I want to calculate total_days_diff = (start_date of next shift - end_date of previous shift)

My Query

select
   e1.start_date,
   e1.end_date,
   datediff(e2.start_date - e1.start_date) as total_days_diff
from emp e1
left join emp e2
on e1.id = e2.id
and e2.start_date > e1.end_date
group by
   e1.start_date,
   e1.end_date

Is there a better way to write above query? I am not getting expected result

You can use lead() :

select t.*,
       datediff(lead(start_date) over (partition by id order by start_date),
                end_date
               ) as days_off
from t;

If you're running a version of MySQL prior to 8.0 and don't have access to the LEAD() function, you can use a self join on the start_date of the second table being the minimum start_date greater than the start_date of the first table:

SELECT e1.*, DATEDIFF(e2.start_date, e1.end_date) AS total_days_diff
FROM emp e1
LEFT JOIN emp e2 ON e2.id = e1.id 
                AND e2.start_date = (SELECT MIN(start_date) 
                                     FROM emp e3
                                     WHERE e3.id = e1.id
                                       AND e3.start_date > e1.start_date)
ORDER BY e1.id, e1.start_date

Output:

id  start_date  end_date    total_days_diff
1   2019-01-05  2019-01-11  4
1   2019-01-15  2019-01-18  7
1   2019-01-25  2019-01-31  (null)
2   2019-01-13  2019-01-17  4
2   2019-01-21  2019-01-28  (null)

Demo on SQLFiddle

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