MySQL - 相同类型的行之间的时间差

时间:2015-06-12 01:38:33

标签: mysql

我有一个包含agent_ids列表,previous_status,新状态和时间戳的表。我试图通过代理确定每个状态更改之间的时间差,以确定代理在特定状态中处于活动状态的时间。

例如:

+------+--------------+--------------+----------------+----------------------+
| id   |  agent_id    |   old_status |   new_status   |  date_time           |
+----------------------------------------------------------------------------+
|  1   |      1       |     offline  |      online    |  2015-06-11 09:00:01 |
|  2   |      1       |     online   |      busy      |  2015-06-11 09:30:23 |
|  3   |      3       |     offline  |      online    |  2015-06-11 09:31:27 |
|  4   |      1       |     busy     |      offline   |  2015-06-11 09:31:45 |
|  5   |      3       |     online   |      offline   |  2015-06-11 09:32:10 |
+----------------------------------------------------------------------------+ 

目标是创建一个带有time_difference列的新结果表, 例如,第5行的time_difference列应该是43秒,这是第5行(agent_id 3的最新状态)与第3行(agent_id 3的先前状态)之间的差异。同样,第4行的time_difference应该是第4行和第2行之间存在差异。

2 个答案:

答案 0 :(得分:0)

你可以按照

的方式做点什么
SELECT id, agent_id, old_status, new_status, date_time, seconds
  FROM
(
SELECT id, agent_id, old_status, new_status, date_time, 
       IF(@a = agent_id, TIMESTAMPDIFF(SECOND, @p, date_time), NULL) seconds,
       @a := agent_id, @p := date_time
  FROM table1 t CROSS JOIN (SELECT @p := NULL, @a := NULL) i
 ORDER BY agent_id, id
) q

输出:

+------+----------+------------+------------+---------------------+---------+
| id   | agent_id | old_status | new_status | date_time           | seconds |
+------+----------+------------+------------+---------------------+---------+
|    1 |        1 | offline    | online     | 2015-06-11 09:00:01 |    NULL |
|    2 |        1 | online     | busy       | 2015-06-11 09:30:23 |    1822 |
|    4 |        1 | busy       | offline    | 2015-06-11 09:31:45 |      82 |
|    3 |        3 | offline    | online     | 2015-06-11 09:31:27 |    NULL |
|    5 |        3 | online     | offline    | 2015-06-11 09:32:10 |      43 |
+------+----------+------------+------------+---------------------+---------+

这是 SQLFiddle 演示

答案 1 :(得分:0)

您可以使用相关子查询在没有变量的情况下处理此问题:

select t.*,
       timestampdiff(second, t.date_time, t.next_date_time) as secs
from (select t.*,
             (select t2.date_time
              from table t2
              where t2.agent_id = t.agent_id and
                    t2.date_time > t.date_time
              order by t2.date_time
              limit 1
             ) as next_date_time
      from table t
     ) t