微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MySQL 中 2 行之间的时间差

如何解决MySQL 中 2 行之间的时间差

我有下表

交易ID 用户名 交易日期时间
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 的事务之间的时间差。 像这样:

交易ID 用户名 交易日期时间 时差
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

但我使用的是 MySQL 5.5 版本,不支持 PARTITION BY 函数。也许还有其他方法? – 瓦鲁赞·斯捷潘扬

SELECT t1.*,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 中的上一个日期/时间:

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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。