How to combine two rows and calculate the time difference between two timestamp values in MySQL?

前端 未结 6 1021
误落风尘
误落风尘 2020-12-06 06:14

I have a situation that I\'m sure is quite common and it\'s really bothering me that I can\'t figure out how to do it or what to search for to find a relevant example/soluti

6条回答
  •  一个人的身影
    2020-12-06 06:59

    How about this:

    SELECT start_log.ts AS start_time, end_log.ts AS end_time
    FROM log AS start_log
    INNER JOIN log AS end_log ON (start_log.name = end_log.name AND end_log.ts > start_log.ts)
    WHERE NOT EXISTS (SELECT 1 FROM log WHERE log.ts > start_log.ts AND log.ts < end_log.ts)
     AND start_log.eventtype = 'start'
     AND end_log.eventtype = 'stop'
    

    This will find each pair of rows (aliased as start_log and end_log) with no events in between, where the first is always a start and the last is always a stop. Since we disallow intermediate events, a start that's not immediately followed by a stop will naturally be excluded.

提交回复
热议问题