mySQL 查询返回给定时间段的最小状态持续时间

问题描述 投票:0回答:1

我在 MySQL 数据库表中有以下数据,我想计算给定时间段的最短持续时间

where state = 1
,以放入 Grafana 统计数据中。

在此表格片段中,所需的结果将是第 10 行和第 8 行之间的

timestampdiff()
,即 2 分钟。

id loc 温度 状态 日期时间
1 room_1 19.4 0 2022-12-29 18:14:09
2 room_1 19.3 0 2022-12-29 18:15:09
3 room_1 19.2 1 2022-12-29 18:16:09
4 room_1 19.2 1 2022-12-29 18:17:09
5 room_1 19.2 1 2022-12-29 18:18:09
6 room_1 19.2 0 2022-12-29 18:19:10
7 room_1 19.2 0 2022-12-29 18:20:10
8 room_1 19.1 1 2022-12-29 18:21:10
9 room_1 19.0 1 2022-12-29 18:22:10
10 room_1 19.0 0 2022-12-29 18:23:10

我已经尝试了很多来自 chatGPT 的错误解决方案,出于明显的原因我不会在这里发布。

周期部分使用 Grafana 全局变量

WHERE $__timeFilter(datetime)
非常简单,使用它我可以计算 total 持续时间
WHERE state = 1 AND $__timeFilter(datetime)
因为记录生成是在 1 分钟的基础上进行的,这使得对二进制 0/1 状态列求和一个简单的(显然不需要
state = 1
)。

我完全迷失了尝试在一段时间内处理持续时间。

mysql sql duration
1个回答
0
投票

您的查询要求有点复杂,我不得不使用windows函数-LAG来获取结果。以下是您需要的查询。

WITH temp_prev_state AS (
SELECT id, loc, temp, state, datetime_, LAG(state,1)  OVER(  ORDER BY datetime_  ) AS prev_state FROM testDB.Temperature
), latest_on_off_stateSession AS (
(SELECT * from temp_prev_state where state = '0' and prev_state = '1' ORDER BY datetime_ DESC LIMIT 1 ) 
UNION
(SELECT * from temp_prev_state where state = '1' and prev_state = '0' ORDER BY datetime_ DESC LIMIT 1 )
), lat_on_off_prev_dt AS (
SELECT *, LAG(datetime_,1)  OVER(  ORDER BY datetime_  ) AS prev_datetime_ FROM latest_on_off_stateSession
)
select id, loc, temp, state, datetime_, ABS(TIMESTAMPDIFF(MINUTE,datetime_ ,prev_datetime_)) AS abs_Time_Diff_Mins FROM lat_on_off_prev_dt


查询的输出:

----------------------------可选---------------- ------------------

我在mariadb-mysql中复制了数据。如果您愿意,可以运行以下代码在 mariadb 中生成数据。然后执行查询。

DROP TABLE IF EXISTS Temperature;

CREATE TABLE Temperature (
    id INT NOT NULL UNIQUE KEY,
    loc VARCHAR(100) NOT NULL,
    temp DOUBLE NOT NULL,
    state  INT NOT NULL,
    datetime_ TIMESTAMP NOT NULL
);

Insert into Temperature VALUES 
(1,"room_1",19.4,0,"2022-12-29 18:14:09"),
(2,"room_1",19.3,0,"2022-12-29 18:15:09"),
(3,"room_1",19.2,1,"2022-12-29 18:16:09"),
(4,"room_1",19.2,1,"2022-12-29 18:17:09"),
(5,"room_1",19.2,1,"2022-12-29 18:18:09"),
(6,"room_1",19.2,0,"2022-12-29 18:19:10"),
(7,"room_1",19.2,0,"2022-12-29 18:20:10"),
(8,"room_1",19.1,1,"2022-12-29 18:21:10"),
(9,"room_1",19.0,1,"2022-12-29 18:22:10"),
(10,"room_1",19.0,0,"2022-12-29 18:23:10")

© www.soinside.com 2019 - 2024. All rights reserved.