我有一个这样的MySql表:
+-------+---------------------+---------------------+------------+------------+
| id | starttime | endtime | startv | endv |
+-------+---------------------+---------------------+------------+------------+
| 66612 | 2018-01-15 17:14:00 | 2018-01-15 17:14:59 | 0.01 | 1.002 |
| 66611 | 2018-01-15 17:13:00 | 2018-01-15 17:13:59 | 5.002 | 0.211 |
| 66610 | 2018-01-15 17:12:00 | 2018-01-15 17:12:59 | 1.001 | 2.011 |
| 66609 | 2018-01-15 17:11:00 | 2018-01-15 17:11:59 | 0.678 | 0.751 |
| 66607 | 2018-01-15 17:10:00 | 2018-01-15 17:10:59 | 0.201 | 1.752 |我可以在一个时间范围内分组为5分钟的间隔,如下所示:
SELECT * from activation
GROUP BY UNIX_TIMESTAMP(starttime) DIV 900
ORDER BY starttime DESC;我当前的输出是:
| 2018-01-15 17:10:00 | 2018-01-15 17:10:59 | 0.201 | 1.752 |这给了我一个按starttime和正确的"startv“(表中的0.201)分组的表,我需要的是将它与一个包含"endv”值的列连接起来,该列与组的最后一个值(最后一个"endtime“1.002)匹配,而不是1.752和正确的"endtime”,例如:
+---------------------+---------------------+------------+------------+
| starttime | endtime | startv | endv |
+---------------------+---------------------+------------+------------+
| 2018-01-15 17:10:00 | 2018-01-15 17:14:59 | 0.201 | 1.002 |发布于 2018-01-18 08:08:09
编写一个子查询,获取每个组中的第一个和最后一个时间戳,然后与这些时间戳连接以获得相应的startv和endv。
SELECT r.starttime, r.endtime, afirst.startv, alast.endv
FROM (SELECT MIN(starttime) as starttime, MAX(endtime) AS endtime
FROM activation
GROUP BY UNIX_TIMESTAMP(starttime) DIV 300) AS r
JOIN activation AS afirst ON afirst.starttime = r.starttime
JOIN activation AS alast ON alast.endtime = r.endtime
ORDER BY r.starttime DESC对于5分钟的间隔,你应该除以300,而不是900 (即15分钟)。
https://stackoverflow.com/questions/48311248
复制相似问题