简体   繁体   中英

calculate date difference between consecutive rows in mysql

I have a TABLE in mysql with Columns:

id, created_time, name

Every row has id and the date time when it has been created. For example below:

id     created_on              name
1      2020-12-03 13:15:09     john
2      2020-11-08 14:11:19     john
3      2020-10-06 14:11:19     john
4      2020-09-12 14:11:19     john

Want to show result in which the difference between 2 rows is greater than 30 days

Expected Output: -

id    created_on             name
2     2020-11-08 14:11:19    john
4     2020-09-12 14:11:19    john

I have tried with below query but failed as it shows all the data.

SELECT id
     , name
  FROM
     ( SELECT MIN(created_on) start_time
            , id
            , name 
         FROM table1 
        WHERE name = 'john'  
        GROUP  
           BY id
     ) start_action
  JOIN
     ( SELECT MAX(created_on) close_time 
            , id
            , name 
         FROM table1 
        WHERE name = 'john' 
        GROUP 
           BY id
     ) close_action
 USING (id,name)
 WHERE name = 'john'

I am using Mysql 5.6 version Request to please help

You could use LEAD here for a MySQL 8+ solution:

WITH cte AS (
    SELECT *, LEAD(created_time) OVER (ORDER BY id) lead_created_time,
              LAG(created_time) OVER (ORDER BY id) lag_created_time
    FROM yourTable
)

SELECT id, created_time
FROM cte
WHERE ABS(DATEDIFF(lead_created_time, created_time)) > 30 OR
      ABS(DATEDIFF(lag_created_time, created_time)) > 30;

Demo

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