简体   繁体   English

MySQL中2行时间差

[英]Time difference between 2 rows in MySQL

I have the following table我有下表

TransactionID交易ID UserID用户身份 TransactionDateTime交易日期时间
1 1 1 1 '2021-04-22 11:00:00' '2021-04-22 11:00:00'
2 2 2 2 '2021-04-22 11:00:11' '2021-04-22 11:00:11'
3 3 1 1 '2021-04-22 11:00:22' '2021-04-22 11:00:22'
4 4 3 3 '2021-04-22 11:00:33' '2021-04-22 11:00:33'
5 5 3 3 '2021-04-22 11:00:44' '2021-04-22 11:00:44'
6 6 1 1 '2021-04-22 11:00:55' '2021-04-22 11:00:55'

I want to see the time difference between transactions for each UserID.我想查看每个 UserID 的事务之间的时间差。 Something like this:像这样的东西:

TransactionID交易ID UserID用户身份 TransactionDateTime交易日期时间 TimeDifference时间差异
1 1 1 1 '2021-04-22 11:00:00' '2021-04-22 11:00:00' NULL NULL
2 2 2 2 '2021-04-22 11:00:11' '2021-04-22 11:00:11' NULL NULL
3 3 1 1 '2021-04-22 11:00:22' '2021-04-22 11:00:22' 00:22 00:22
4 4 3 3 '2021-04-22 11:00:33' '2021-04-22 11:00:33' NULL NULL
5 5 3 3 '2021-04-22 11:00:44' '2021-04-22 11:00:44' 00:11 00:11
6 6 1 1 '2021-04-22 11:00:55' '2021-04-22 11:00:55' 00:33 00:33

Is there any possible way to do that?有没有办法做到这一点?

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.但我使用的是 MySQL 5.5 版本,不支持 PARTITION BY function。 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 https://dbfiddle.uk/?rdbms=mysql_5.5&fiddle=b7d43521afc8fe6623f152343bb88d4b

I would suggest a correlated subquery to get the previous date/time in older versions of MySQL:我建议使用相关子查询来获取旧版本 MySQL 中的上一个日期/时间:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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