嗨,我刚刚接触了mysql。我有一张这样的桌子:
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
----------------------------------------------
请帮忙。
答案 0 :(得分:1)
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 |
+---------------------+------+-------------+