CREATE TABLE `status` (
`id` int(11) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`state` int(11) DEFAULT NULL
)
set @last_date = NULL;
select @last_date as start_date,
date as end_date,
case when state = 1 then @last_date := date end as ignore_me,
case when state = 0 then (unix_timestamp(date) - unix_timestamp(@last_date)) / 60 end as duration
from status
where id = 1
order by date
给你这样的输出:
+---------------------+---------------------+---------------------+----------+
| start_date | end_date | ignore_me | duration |
+---------------------+---------------------+---------------------+----------+
| 2012-11-20 01:16:00 | 2012-11-20 01:00:00 | 2012-11-20 01:00:00 | NULL |
| 2012-11-20 01:00:00 | 2012-11-20 01:15:00 | NULL | 15.0000 |
| 2012-11-20 01:00:00 | 2012-11-20 01:16:00 | 2012-11-20 01:16:00 | NULL |
| 2012-11-20 01:16:00 | 2012-11-20 01:20:00 | NULL | 4.0000 |
+---------------------+---------------------+---------------------+----------+
只取具有持续时间的行来表现出色:
select * from (
...
) foo
where duration is not null
+---------------------+---------------------+-----------+----------+
| start_date | end_date | ignore_me | duration |
+---------------------+---------------------+-----------+----------+
| 2012-11-20 01:00:00 | 2012-11-20 01:15:00 | NULL | 15.0000 |
| 2012-11-20 01:16:00 | 2012-11-20 01:20:00 | NULL | 4.0000 |
+---------------------+---------------------+-----------+----------+