从ON OFF时间戳计算总的ON时间

时间:2019-09-22 05:16:15

标签: mysql

我有一个表,其中包含交替的ON&OFF事件及其时间戳。如何计算每次打开和关闭之间的总时间?

Status        Timestamp
============================
ON       2019-01-01 07:00:00
OFF      2019-01-01 08:30:00
ON       2019-01-01 09:00:00
OFF      2019-01-01 10:00:00
ON       2019-01-01 10:30:00
OFF      2019-01-01 11:30:00

2 个答案:

答案 0 :(得分:1)

请考虑以下内容...

CREATE TABLE my_table
(id  INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
 dt DATETIME NOT NULL,
 status VARCHAR(5) NOT NULL
);

INSERT INTO my_table VALUES
(1,'2015-01-01 13:00:00','ON'),
(2,'2015-01-01 13:10:00','OFF'),
(3,'2015-01-01 13:20:00','ON'),
(4,'2015-01-01 13:30:00','OFF'),
(5,'2015-01-01 13:35:00','ON'),
(6,'2015-01-01 13:40:00','OFF'),
(7,'2015-01-01 13:50:00','ON'),
(8,'2015-01-01 15:00:00','OFF');

 SELECT x.*, 
 TIMEDIFF(MIN(y.dt),x.dt) AS TimeDiff 
 FROM my_table AS x 
 INNER JOIN my_table AS y ON y.dt >= x.dt 
 WHERE x.status = 'ON' AND y.status = 'OFF' 
 GROUP 
 BY x.id;

有关更多信息,请参阅DB FIDDLE: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=00dc040da540f852f08b2f02750bc16d

答案 1 :(得分:0)

CREATE TABLE events (
  `status` VARCHAR(3),
  `timestamp` VARCHAR(19)
);

INSERT INTO events
  (`status`, `timestamp`)
VALUES
  ('ON', '2019-01-01 07:00:00'),
  ('OFF', '2019-01-01 08:30:00'),
  ('ON', '2019-01-01 09:00:00'),
  ('OFF', '2019-01-01 10:00:00'),
  ('ON', '2019-01-01 10:30:00'),
  ('OFF', '2019-01-01 11:30:00');

SELECT 
TIME_FORMAT(SEC_TO_TIME(TIME_TO_SEC(
            SUM(TIMEDIFF(offtime, ontime))
          )), '%H:%i')
                 AS total FROM (
SELECT e.timestamp AS offtime, (SELECT  timestamp 
                               FROM events AS st WHERE st.timestamp < e.timestamp AND st.status = "ON"
                               ORDER BY st.timestamp DESC LIMIT 1) AS ontime
FROM events AS e WHERE e.status='OFF') AS onoffs

选择每个OFF记录,将最新的ON记录加入其中,对时间范围求和。使用您的数据可以得出结果:total 03:30

不考虑开放范围。例如。如果数据系列从OFF开始;否则,如果它以ON结尾,则到当前时刻为止的时间将不计算在内。

https://www.db-fiddle.com/f/hr27GhACxGd7ZvFaa52xiK/0#