[英]MySQL Query to return total hours for state information
I have a mysql table capturing state information for a signal every minute in MySQL table as follows: 我有一个mysql表,每分钟捕获一次MySQL表中信号的状态信息,如下所示:
ID | state | timestamp |
--------------------------------------
'sig1'| 'red' | '2017-07-10 15:30:21'
'sig1'| 'green' | '2017-07-10 15:31:26'
'sig1'| 'green' | '2017-07-10 15:32:24'
'sig1'| 'red' | '2017-07-10 15:33:29'
'sig1'| 'red' | '2017-07-10 15:34:30'
'sig1'| 'red' | '2017-07-10 15:35:15'
I need to come up with a query where it result should be the most recent time 'sig1' was in 'red' state for more than 5 minutes consecutively , the output of the query should be 我需要提出一个查询,查询结果应该是最近一次'sig1'连续处于'红色'状态超过5分钟 ,查询的输出应该是
ID | state| duration | start_time | end_time
So if you guys can help me with the query, that would be great! 因此,如果你们可以帮助我进行查询,那就太好了!
cheers! 干杯!
SELECT TIMESTAMPDIFF(HOUR,MAXTIME ,MINTIME),ID,state FROM
(
SELECT ID,state,MIN(timestamp)MINTIME,MAX(timestamp) MAXTIME FROM TABLE GROUP BY ID,state
)Z
Try above query. 请尝试上述查询。
You can try something like this: 您可以尝试如下操作:
SELECT t.id,t.consecutive,t.state
,COUNT(*) consecutive_count
,MIN(timestamp) start_time
,MAX(timestamp) end_time
,TIMEDIFF(MAX(timestamp), MIN(timestamp)) AS diff /* for ckeck*/
FROM (SELECT a.* ,
@r:= CASE WHEN @g = a.state AND @h=a.id THEN @r ELSE @r + 1 END consecutive,
@g:= a.state g,
@h:= a.id h
FROM yourtable a
CROSS JOIN (SELECT @g:='', @r:=0, @h:='') t1
ORDER BY id
) t
GROUP BY t.id,t.consecutive,t.state
HAVING (UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(start_time))/60>5
;
Sample data: 样本数据:
CREATE TABLE yourtable (
id VARCHAR(10) NOT NULL ,
state VARCHAR(10) NOT NULL,
timestamp datetime
);
INSERT INTO yourtable VALUES ('sig1','red','2017-07-10 15:30:21');
INSERT INTO yourtable VALUES ('sig1','green','2017-07-10 15:31:26');
INSERT INTO yourtable VALUES ('sig1','green','2017-07-10 15:32:24');
INSERT INTO yourtable VALUES ('sig1','red','2017-07-10 15:33:29');
INSERT INTO yourtable VALUES ('sig1','red','2017-07-10 15:34:30');
INSERT INTO yourtable VALUES ('sig1','red','2017-07-10 15:39:15');
INSERT INTO yourtable VALUES ('sig2','red','2017-07-10 15:15:15');
Output: 输出:
id consecutive state consecutive_count start_time end_time diff
sig1 3 red 3 10.07.2017 15:33:29 10.07.2017 15:39:15 00:05:46
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.