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 |
+---------------------+---------------------+-----------+----------+