MySQL计算煤仓加煤操作间隔时间差的实现需求
连续加煤操作时间差计算方案
表结构说明
nasypka表存储锅炉煤仓煤量数据,结构如下:
ID|datetime |height|refilled 1 |2022-09-01 12:00|101 |1 2 |2022-09-01 12:01|96 |0 3 |2022-09-01 12:02|50 |0 4 |2022-09-01 12:03|10 |0 ... 50|2022-09-05 17:04|105 |1 51|2022-09-05 17:05|104 |0 ... 80|2022-09-15 10:04|99 |1 81|2022-09-15 10:05|98 |0
其中refilled=1表示完成一次加煤操作,需计算连续两次加煤的时间差,ID列无需连续,结果需包含开始时间、结束时间、时间差,可限制显示最近X个时间段。
方案1:升级至MySQL 5.7/8.0(推荐)
MySQL 5.7及以上支持窗口函数LEAD(),写法简洁高效:
SELECT datetime AS begin_date, LEAD(datetime) OVER (ORDER BY datetime) AS end_date, -- 按小时计算时间差 TIMESTAMPDIFF(HOUR, datetime, LEAD(datetime) OVER (ORDER BY datetime)) AS difference_hours, -- 或保留时分秒格式的时间差 TIMEDIFF(LEAD(datetime) OVER (ORDER BY datetime), datetime) AS difference FROM nasypka WHERE refilled = 1 ORDER BY datetime -- 限制显示最近5个时间段,可按需修改数字 LIMIT 5;
说明
LEAD(datetime)按时间顺序为每条加煤记录取下一条加煤记录的时间TIMESTAMPDIFF直接输出小时数差值,TIMEDIFF输出HH:MM:SS格式的差值- 过滤
refilled=1仅保留加煤操作记录,最后按时间排序并可选限制结果数量
方案2:保留MySQL 5.5版本
若无法升级,可通过自关联+子查询实现:
SELECT n1.datetime AS begin_date, n2.datetime AS end_date, TIMESTAMPDIFF(HOUR, n1.datetime, n2.datetime) AS difference_hours, TIMEDIFF(n2.datetime, n1.datetime) AS difference FROM nasypka n1 JOIN nasypka n2 ON n2.datetime = ( SELECT MIN(datetime) FROM nasypka WHERE refilled = 1 AND datetime > n1.datetime ) WHERE n1.refilled = 1 ORDER BY n1.datetime -- 限制显示最近5个时间段,可按需修改数字 LIMIT 5;
说明
- 子查询为当前加煤记录找到后续最早的加煤记录时间
- 最后一条加煤记录因无后续记录会被自动过滤,符合需求
内容的提问来源于stack exchange,提问作者PedroKV
相关产品推荐
相关产品推荐

