简体   繁体   中英

Time difference between adjacent rows in one column of one mysql table

I have a table with some 100.000 rows having this structure:

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

For each row, I would like to calculate the days between the timestamp of this and the previous row. As you can see, the id is not continuous, this the table contains different events and I would like to compare only the timestamp of one specific event over time.

I know, that for the comparison of tow datas, DATEDIFF can be used, and I would define the two rows with a query, that selects the row by the specific id. But as I have many 1000 rows, I am searching for a way to somehow loop through the whole table.

Unfortunately my sql knowledge is limited and searching did not reveal an example, close enough to my question, that I would continue form there. I would be very thankful for any hint.

If you are running MySQL 8.0, you can just use lag() . Say you want the difference in seconds:

select t.*,
    timestampdiff(
        second, 
        lag(timestamp) over(partition by eventtype order by id),
        timestamp
    ) diff
from mytable t

In earlier versions, one alternative is a correlated subquery:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM