状态更改之间MySQL中的时差

时间:2019-03-22 13:06:52

标签: 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

能请你帮我吗?

非常感谢。

1 个答案:

答案 0 :(得分:1)

首先,您必须消除所有对结果无用的行,例如在使用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

请参见demo
结果:

| 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 |