MySQL 中 2 行之间的时间差

Time difference between 2 rows in MySQL

我有以下table

TransactionID UserID TransactionDateTime
1 1 '2021-04-22 11:00:00'
2 2 '2021-04-22 11:00:11'
3 1 '2021-04-22 11:00:22'
4 3 '2021-04-22 11:00:33'
5 3 '2021-04-22 11:00:44'
6 1 '2021-04-22 11:00:55'

我想查看每个 UserID 的交易时间差。 像这样:

TransactionID UserID TransactionDateTime TimeDifference
1 1 '2021-04-22 11:00:00' NULL
2 2 '2021-04-22 11:00:11' NULL
3 1 '2021-04-22 11:00:22' 00:22
4 3 '2021-04-22 11:00:33' NULL
5 3 '2021-04-22 11:00:44' 00:11
6 1 '2021-04-22 11:00:55' 00:33

有什么办法可以做到吗?

SELECT *,
       SEC_TO_TIME(TIMESTAMPDIFF(SECOND, 
                                 TransactionDateTime,
                                 LAG(TransactionDateTime) OVER (PARTITION BY UserID
                                                                ORDER BY TransactionDateTime))) TimeDifference
FROM table
ORDER BY TransactionDateTime

but I'm using MySQL 5.5 version and the PARTITION BY function isn't supported. Maybe there is other way? – Varuzhan Stepanyan

SELECT t1.*, 
       SEC_TO_TIME(TIMESTAMPDIFF(SECOND, t2.TransactionDateTime, t1.TransactionDateTime)) TimeDifference
FROM table t1
LEFT JOIN table t2 ON t1.UserID = t2.UserID 
                 AND t1.TransactionDateTime > t2.TransactionDateTime
WHERE NOT EXISTS ( SELECT NULL
                   FROM table t3
                   WHERE t1.UserID = t3.UserID 
                     AND t1.TransactionDateTime > t3.TransactionDateTime
                     AND t3.TransactionDateTime > t2.TransactionDateTime )
ORDER BY t1.TransactionID;

https://dbfiddle.uk/?rdbms=mysql_5.5&fiddle=b7d43521afc8fe6623f152343bb88d4b

我建议使用相关子查询来获取旧版本 MySQL 中的前一个 date/time:

select t.*,
       timediff(TransactionDateTime, prev_TransactionDateTime) as timedifference
from (select t.*,
             (select max(t2.TransactionDateTime)
              from t t2
              where t2.UserId = t.UserId and
                    t2.TransactionDateTime < t.TransactionDateTime
             ) as prev_TransactionDateTime
      from t
     ) t;