gpt4 book ai didi

mysql - 计算mysql时间戳之间的相差分钟数

转载 作者:行者123 更新时间:2023-11-29 12:50:16 24 4
gpt4 key购买 nike

嗨,我是 mysql 的新手。我有一张这样的 table :

TIME                |  USER        | interval
----------------------------------------------
2014-07-06 23:00:42 | ngm |
----------------------------------------------
2014-07-06 23:01:33 | ngm |
----------------------------------------------
2014-07-06 23:02:41 | cpg |
----------------------------------------------
2014-07-06 23:03:48 | ngm |
----------------------------------------------
2014-07-06 23:13:09 | cpg |
----------------------------------------------
2014-07-06 23:18:31 | cpg |
----------------------------------------------

我需要帮助来计算“用户”的“时间”之间的分钟差异,因此它看起来像这样:

TIME                |  USER        | interval
----------------------------------------------
2014-07-06 23:00:42 | ngm | 0
----------------------------------------------
2014-07-06 23:01:33 | ngm | 1
----------------------------------------------
2014-07-06 23:02:41 | cpg | 0
----------------------------------------------
2014-07-06 23:03:48 | ngm | 2
----------------------------------------------
2014-07-06 23:13:09 | cpg | 11
----------------------------------------------
2014-07-06 23:18:31 | cpg | 5
----------------------------------------------

请帮忙。

最佳答案

 DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(time DATETIME NOT NULL,user CHAR(3) NOT NULL,PRIMARY KEY(time,user));

INSERT INTO my_table VALUES
('2014-07-06 23:00:42','ngm'),
('2014-07-06 23:01:33','ngm'),
('2014-07-06 23:02:41','cpg'),
('2014-07-06 23:03:48','ngm'),
('2014-07-06 23:13:09','cpg'),
('2014-07-06 23:18:31','cpg');

mysql> SELECT * FROM my_table;
+---------------------+------+
| time | user |
+---------------------+------+
| 2014-07-06 23:00:42 | ngm |
| 2014-07-06 23:01:33 | ngm |
| 2014-07-06 23:02:41 | cpg |
| 2014-07-06 23:03:48 | ngm |
| 2014-07-06 23:13:09 | cpg |
| 2014-07-06 23:18:31 | cpg |
+---------------------+------+

SELECT x.*
, COALESCE(
SEC_TO_TIME(
ROUND(TIME_TO_SEC(
TIMEDIFF(x.time,MAX(y.time))
)/60
)*60
),0
) my_interval -- <-- can probably make shorter
FROM my_table x
LEFT
JOIN my_table y
ON y.user = x.user
AND y.time < x.time
GROUP
BY time
, user;
+---------------------+------+-------------+
| time | user | my_interval |
+---------------------+------+-------------+
| 2014-07-06 23:00:42 | ngm | 0 |
| 2014-07-06 23:01:33 | ngm | 00:01:00 |
| 2014-07-06 23:02:41 | cpg | 0 |
| 2014-07-06 23:03:48 | ngm | 00:02:00 |
| 2014-07-06 23:13:09 | cpg | 00:10:00 |
| 2014-07-06 23:18:31 | cpg | 00:05:00 |
+---------------------+------+-------------+

关于mysql - 计算mysql时间戳之间的相差分钟数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24860825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com