我正在使用MySQL,并且有一个名为“ results”的表,该表存储监视器的结果,该监视器确定服务在特定时间是启动还是关闭.
+-----------+------------+---------------------+--------+
| result_id | service_id | time_stamp | result |
+-----------+------------+---------------------+--------+
| 1 | 1 | 0000-00-00 00:01:00 | down |
| 2 | 1 | 0000-00-00 00:02:00 | up |
| 3 | 1 | 0000-00-00 00:03:00 | up |
| 4 | 1 | 0000-00-00 00:04:00 | up |
| 5 | 1 | 0000-00-00 00:05:00 | down |
| 6 | 1 | 0000-00-00 00:06:00 | down |
| 7 | 1 | 0000-00-00 00:07:00 | up |
| 8 | 1 | 0000-00-00 00:08:00 | down |
| 9 | 1 | 0000-00-00 00:09:00 | up |
| 10 | 2 | 0000-00-00 00:03:00 | up |
+-----------+------------+---------------------+--------+
我想获得一个结果表,该表查看给定服务的结果,并返回第一次记录为关闭的时间以及最后一次(连续)记录的时间,反之亦然.这将帮助我记录服务的停机时间.
我要寻找的结果看起来像这样.
对于service_id 1 …
+-----------------------+---------------------+--------+
| start_time | end_time | result |
+-----------------------+---------------------+--------+
| 0000-00-00 00:01:00 | 0000-00-00 00:01:00 | down |
| 0000-00-00 00:02:00 | 0000-00-00 00:04:00 | up |
| 0000-00-00 00:05:00 | 0000-00-00 00:06:00 | down |
| 0000-00-00 00:07:00 | 0000-00-00 00:07:00 | up |
| 0000-00-00 00:08:00 | 0000-00-00 00:08:00 | down |
| 0000-00-00 00:09:00 | 0000-00-00 00:09:00 | up |
+-----------------------+---------------------+--------+
我可以很容易地用Java或PHP获得此信息,但我更喜欢使用SQL查询.我的SQL技能不是特别高级.我将如何处理?
解决方法:
解决此问题的最简单方法是使用变量,我认为最简单的方法是添加两个变量,一个变量为“ up”的数目,另一变量为“ down”的数目,直至任何给定的行.给定的升序序列对于前面的“降”次数具有恒定值,反之亦然.此逻辑可用于聚合.
结果查询为:
select result, min(time_stamp) as start_time, max(time_stamp) as end_time
from (select r.*,
(@ups := @ups + (result = 'up')) as ups,
(@downs := @downs + (result = 'down')) as downs
from results r cross join
(select @ups := 0, @downs := 0) vars
where service_id = 1
order by time_stamp
) r
group by result, (case when result = 'up' then downs else ups end);