通过值计算状态下的时间

时间:2018-08-16 16:24:30

标签: mysql sql

我有一个包含时间序列数据的MySQL表,我想按值获取状态下的总时间。

表格如下:

+----------------+---------------------+---------------+------------+
|             id | status_update_time  | current_state | last state |
+----------------+---------------------+---------------+------------+
|            248 | 2017-02-17 05:00:00 |             1 |          0 |
|            248 | 2017-02-17 02:00:00 |             0 |          1 |
|            248 | 2017-02-17 01:00:00 |             1 |          0 |
|            250 | 2017-02-17 06:00:00 |             0 |          1 |
|            250 | 2017-02-17 05:00:00 |             1 |          0 |
|            252 | 2017-02-17 06:00:00 |             0 |          2 |
|            252 | 2017-02-17 03:00:00 |             2 |          0 |
|            254 | 2017-02-17 03:00:00 |             0 |          1 |
|            254 | 2017-02-17 02:00:00 |             1 |          0 |
|            254 | 2017-02-17 01:00:00 |             0 |          1 |
|            254 | 2017-02-17 00:00:00 |             1 |          2 |
+----------------+---------------------+---------------+------------+

我想要的预期输出是:

+----------------+---------------------+----------------+
|             id | state               | time_in_seconds|          
+----------------+---------------------+----------------+
|            248 | 0                   |          10800 |
|            248 | 1                   |           3600 |
|            250 | 1                   |           3600 |
|            252 | 2                   |          10800 |
|            254 | 0                   |           7200 |
|            254 | 1                   |           7200 |
+----------------+---------------------+----------------+

编辑:我无法生成第二张表,但是我想生成第二张表。

使第二张表成为ID 248的逻辑在状态1下总计3600秒,在状态0下总计10800秒。这是因为从2017-02-17 01:00:00到2017-02-17 02:00:00处于1状态,然后从2017-02-17 02:00:00到2017-02-17 05:00:00它处于0状态,然后更改为1状态。

1 个答案:

答案 0 :(得分:1)

SELECT id, cur_state, SUM(duration) as total_time
FROM (
  SELECT id, cur_state,
  (SELECT TIME_TO_SEC(TIMEDIFF(MIN(InnerTable.status_update_time), OuterTable.status_update_time)) FROM t as InnerTable
  WHERE
   InnerTable.last_state = OuterTable.cur_state
   AND
   InnerTable.status_update_time > OuterTable.status_update_time
   AND
   InnerTable.id = OuterTable.id
  ) duration
  FROM t as OuterTable
) anyName
WHERE duration IS NOT NULL
GROUP BY id, cur_state

您可以在此处进行检查:http://sqlfiddle.com/#!9/6a8439/38