如何选择行与过滤器之间的时差

时间:2019-01-09 17:27:50

标签: mysql sql

我正在使用MySQL 5.7计算连续行之间的时间差(以秒为单位)。我有几个问题

  1. 这如何选择上一行用于每个结果行的计算?具体来说,查询的哪一部分实际上在执行此操作?
  2. 如何过滤@diff列以排除0或大于60秒的值?每当我尝试添加WHERE子句时,都会出现错误。
  3. 过滤后,我是否应该可以SUM@diff来获取总时间?

查询

SELECT @diff   AS start,
       created AS end,
       IF(@diff = 0, 0, UNIX_TIMESTAMP(`created`) - UNIX_TIMESTAMP(@diff)) AS diff,
       @diff := created AS endtime
FROM   events,
       (SELECT @diff := 0) AS x
ORDER  BY events.created

源表events

Desc      | Timestamp
-------------------------------
Event 1   | 2019-01-03 17:21:03
Event 2   | 2019-01-03 17:21:03
Event 3   | 2019-01-03 17:21:03
Event 4   | 2019-01-03 17:21:14
Event 5   | 2019-01-03 17:21:16
Event 6   | 2019-01-03 17:25:46

当前结果

start               | end                   | diff      | endtime
-------------------------------------------------------------------------
0                   | 2019-01-03 17:21:03   | 0         | 2019-01-03 17:21:03
2019-01-03 17:21:03 | 2019-01-03 17:21:03   | 0.000000  | 2019-01-03 17:21:03
2019-01-03 17:21:03 | 2019-01-03 17:21:03   | 0.000000  | 2019-01-03 17:21:03
2019-01-03 17:21:03 | 2019-01-03 17:21:14   | 11.00000  | 2019-01-03 17:21:14
2019-01-03 17:21:14 | 2019-01-03 17:21:16   | 2.000000  | 2019-01-03 17:21:16
2019-01-03 17:21:16 | 2019-01-03 17:25:46   | 270.0000  | 2019-01-03 17:25:46

所需结果

start               | end                   | diff      | endtime
-------------------------------------------------------------------------
2019-01-03 17:21:03 | 2019-01-03 17:21:14   | 11.00000  | 2019-01-03 17:21:14
2019-01-03 17:21:14 | 2019-01-03 17:21:16   | 2.000000  | 2019-01-03 17:21:16

1 个答案:

答案 0 :(得分:0)

在MySQL 8+中,您应该使用窗口函数:

SELECT lag(created) over (order by created)   AS start,
       created AS end,
       coalesce(UNIX_TIMESTAMP(created) - UNIX_TIMESTAMP(lag(created) over (order by created)), 0) as diff
FROM events e
ORDER BY e.created;

在早期版本中,您的代码编写得不好,因为MySQL不保证SELECT中表达式的求值顺序。