Search code examples
phpmysqldatediff

Calculate time between timestamps for each 2 rows


I have the below table and as you can see in the table, a user has a BREAK OUT and BREAK IN entry for each of the breaks, but i am struggling to calculate the time spent on each break. Can you guys help? Thanks.

ID  Name      Action     Datetime
 2  John Doe  BREAK OUT  2018-05-24 09:00:41
 3  John Doe  BREAK IN   2018-05-24 09:10:45
 4  John Doe  BREAK OUT  2018-05-24 13:00:49
 5  John Doe  BREAK IN   2018-05-24 13:30:52
 6  John Doe  BREAK OUT  2018-05-24 15:30:56
 7  John Doe  BREAK IN   2018-05-24 15:40:59

Solution

  • E.g.:

    DROP TABLE IF EXISTS my_table;
    
    CREATE TABLE my_table
    (Action VARCHAR(20) NOT NULL,dt DATETIME PRIMARY KEY);
    
    INSERT INTO my_table VALUES
    ('BREAK OUT','2018-05-24 09:00:41'),
    ('BREAK IN','2018-05-24 09:10:45'),
    ('BREAK OUT','2018-05-24 13:00:49'),
    ('BREAK IN','2018-05-24 13:30:52'),
    ('BREAK OUT','2018-05-24 15:30:56'),
    ('BREAK IN','2018-05-24 15:40:59');
    
    SELECT bi.dt
         , SEC_TO_TIME(TIME_TO_SEC(bi.dt)-TIME_TO_SEC(MAX(bo.dt)))x 
      FROM my_table bi 
      JOIN my_table bo 
        ON bo.dt <= bi.dt 
     WHERE bo.action = 'break out' 
       AND bi.action = 'break in' 
     GROUP 
        BY bi.dt;
    
    +---------------------+----------+
    | dt                  | x        |
    +---------------------+----------+
    | 2018-05-24 09:10:45 | 00:10:04 |
    | 2018-05-24 13:30:52 | 00:30:03 |
    | 2018-05-24 15:40:59 | 00:10:03 |
    +---------------------+----------+