使用其中WITH子句无效的旧版MySQL。
从表格开始:
+--------+---------------------+---------------------+
| person | start_time | end_time |
+--------+---------------------+---------------------+
| Alice | 2020-02-27 20:00:00 | 2020-02-27 20:59:59 |
| Alice | 2020-02-27 23:45:00 | 2020-02-27 23:59:59 |
| Alice | 2020-02-28 00:00:00 | 2020-02-28 00:59:59 |
| Alice | 2020-02-28 01:00:00 | 2020-02-28 01:59:59 |
| Bob | 2020-02-27 23:45:00 | 2020-02-27 23:59:59 |
| Cindy | 2020-02-28 02:00:00 | 2020-02-28 02:59:59 |
| Cindy | 2020-02-28 03:00:00 | 2020-02-28 03:36:59 |
+--------+---------------------+---------------------+
我想查询所有相差不到一个小时的人均时长。
+--------+---------------------+---------------------+----------+
| person | start_time | end_time | duration |
+--------+---------------------+---------------------+----------+
| Alice | 2020-02-27 20:00:00 | 2020-02-27 20:59:59 | 3599 |
| Alice | 2020-02-27 23:45:00 | 2020-02-28 01:59:59 | 8064 |
| Bob | 2020-02-27 23:45:00 | 2020-02-27 23:59:59 | 899 |
| Cindy | 2020-02-28 02:00:00 | 2020-02-28 03:36:59 | 5806 |
+--------+---------------------+---------------------+----------+
SELECT `t`.`person`,`t`.`start_time`,`t`.`end_time`,
SUM(TIMESTAMPDIFF(SECOND,`t`.`start_time`,`t`.`end_time`)) AS `duration`,
IF( EXISTS (SELECT * FROM `test` `t1`
WHERE `t1`.`start_time`=TIMESTAMPADD(SECOND,1,`t`.`end_time`) OR TIMESTAMPDIFF(SECOND,`t`.`start_time`,`t1`.`end_time`)=-1),1,0) AS `continuous`
FROM `test` `t`
WHERE TIMESTAMPDIFF(SECOND,`t`.`start_time`,`t`.`end_time`)
BETWEEN 0 AND 3599
GROUP BY `t`.`person`,`continuous`
ORDER BY `t`.`person`,`t`.`start_time`;