一列一列相邻行的时间差mysqltable
Time difference between adjacent rows in one column of one mysql table
我有一个 table,大约 100.000 行具有这种结构:
+------+---------------------+-----------+
| id | timestamp | eventType |
+------+---------------------+-----------+
| 12 | 2015-07-01 16:45:47 | 3001 |
| 103 | 2015-07-10 19:30:14 | 3001 |
| 1174 | 2015-09-03 12:57:08 | 3001 |
+------+---------------------+-----------+
对于每一行,我想计算这一行和上一行的时间戳之间的天数。
如您所见,id 不是连续的,table 包含不同的事件,我只想比较一个特定事件随时间变化的时间戳。
我知道,对于两个数据的比较,可以使用 DATEDIFF,我会用查询定义两行,通过特定的 id 选择行。
但是因为我有很多 1000 行,我正在寻找一种方法来以某种方式遍历整个 table.
不幸的是,我的 sql 知识有限,搜索没有显示足够接近我的问题的例子,我会继续从那里开始。
如果有任何提示,我将不胜感激。
如果你是运行 MySQL 8.0,你可以直接使用lag()
。假设您想要以秒为单位的差异:
select t.*,
timestampdiff(
second,
lag(timestamp) over(partition by eventtype order by id),
timestamp
) diff
from mytable t
在早期版本中,一种替代方法是相关子查询:
select t.*,
timestampdiff(
second,
(select timestamp from mytable t1 where t1.eventtype = t.eventtype and t1.id < t.id order by t1.id desc limit 1),
timestamp
) diff
from mytable t
我有一个 table,大约 100.000 行具有这种结构:
+------+---------------------+-----------+
| id | timestamp | eventType |
+------+---------------------+-----------+
| 12 | 2015-07-01 16:45:47 | 3001 |
| 103 | 2015-07-10 19:30:14 | 3001 |
| 1174 | 2015-09-03 12:57:08 | 3001 |
+------+---------------------+-----------+
对于每一行,我想计算这一行和上一行的时间戳之间的天数。 如您所见,id 不是连续的,table 包含不同的事件,我只想比较一个特定事件随时间变化的时间戳。
我知道,对于两个数据的比较,可以使用 DATEDIFF,我会用查询定义两行,通过特定的 id 选择行。 但是因为我有很多 1000 行,我正在寻找一种方法来以某种方式遍历整个 table.
不幸的是,我的 sql 知识有限,搜索没有显示足够接近我的问题的例子,我会继续从那里开始。 如果有任何提示,我将不胜感激。
如果你是运行 MySQL 8.0,你可以直接使用lag()
。假设您想要以秒为单位的差异:
select t.*,
timestampdiff(
second,
lag(timestamp) over(partition by eventtype order by id),
timestamp
) diff
from mytable t
在早期版本中,一种替代方法是相关子查询:
select t.*,
timestampdiff(
second,
(select timestamp from mytable t1 where t1.eventtype = t.eventtype and t1.id < t.id order by t1.id desc limit 1),
timestamp
) diff
from mytable t