mysql - MySQL状态变化之间的时间差
问题描述
我有一张桌子,上面有灯及其相应的状态:
timestamp name state
2019-03-07 11:16:32 Light_A 0
2019-03-07 12:36:32 Light_A 1
2019-03-07 13:15:12 Light_A 0
2019-03-08 02:11:45 Light_A 1
2019-03-08 02:18:45 Light_A 1
2019-03-08 02:22:45 Light_A 0
2019-03-18 03:14:45 Light_B 0
2019-03-18 03:16:45 Light_B 1
2019-03-18 03:18:45 Light_B 1
2019-03-18 03:20:45 Light_B 0
2019-03-19 17:20:12 Light_B 0
2019-03-19 17:22:12 Light_B 1
2019-03-19 17:23:12 Light_B 0
我想测量每个灯打开了多少小时。
到目前为止,我得到了:
SELECT x.*, TIMEDIFF(MIN(y.timestamp),x.timestamp)diff
FROM data x
JOIN data y
ON y.timestamp >= x.timestamp
WHERE x.state = 1 AND y.state = 0
GROUP
BY x.timestamp;
除非两个连续的行具有相同的 State = 1,否则效果很好
上面的命令返回:
timestamp name state diff
2019-03-07 12:36:32 Light_A 1 00:38:40
2019-03-08 02:11:45 Light_A 1 00:11:00
2019-03-08 02:18:45 Light_A 1 00:04:00
2019-03-18 03:16:45 Light_B 1 00:04:00
2019-03-18 03:18:45 Light_B 1 00:02:00
2019-03-19 17:22:12 Light_B 1 00:01:00
相反,我希望得到这样的结果:
timestamp name state diff
2019-03-07 12:36:32 Light_A 1 00:38:40
2019-03-08 02:11:45 Light_A 1 00:11:00
2019-03-18 03:16:45 Light_B 1 00:04:00
2019-03-19 17:22:12 Light_B 1 00:01:00
请你帮助我好吗?
提前谢谢了。
解决方案
首先您必须消除所有对结果没有贡献的行,例如一行与state = 1
之后的一行,state = 1
然后获取该行state = 0
以计算差异:
select
t.timestamp,
t.name,
t.state
timediff(coalesce(
(select timestamp from tablename where state = 0 and timestamp =
(select min(timestamp) from tablename where timestamp > t.timestamp and state = 0)), now()),
t.timestamp) diff
from tablename t
where
t.state = 1 and coalesce((select state from tablename where timestamp =
(select max(timestamp) from tablename where timestamp < t.timestamp)), 0) = 0
查看演示
结果:
| timestamp | name | state | diff |
| ------------------- | ------- | ----- | -------- |
| 2019-03-07 12:36:32 | Light_A | 1 | 00:38:40 |
| 2019-03-08 02:11:45 | Light_A | 1 | 00:11:00 |
| 2019-03-18 03:16:45 | Light_B | 1 | 00:04:00 |
| 2019-03-19 17:22:12 | Light_B | 1 | 00:01:00 |
推荐阅读
- encoding - UTF-8 如何最终得到比 UTF-16 更大的位
- javascript - 附加项目后滚动事件不起作用
- java - fetch unique data from one to many relationship in hql and apply limit
- memory-management - 什么类型的输入会减慢动态内存分配器 malloc() 和 free() 的执行时间?
- r - r 中列中唯一值组合的总和
- node.js - In the linked question, what does the op talk about regarding installing node.js in the working directory?
- ios - Integrate google-ad-manager with ios framework
- amazon-cloudformation - How to update secret string using cludformation?
- c# - Summing the values of an array to a specific value
- dart - 在飞镖中使用枚举时是否可以返回默认值