gpt4 book ai didi

mysql - 分组为间隔多列

转载 作者:行者123 更新时间:2023-11-29 05:57:16 25 4
gpt4 key购买 nike

我有一个像这样的 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      |

这给了我一个按开始时间和正确的“startv”(表中的 0.201)分组的表,我需要的是将它与包含与组的最后一个值匹配的“endv”值的列连接起来(最后一个“结束时间”1.002) 而不是 1.752,正确的“结束时间”如下:

+---------------------+---------------------+------------+------------+
| starttime | endtime | startv | endv |
+---------------------+---------------------+------------+------------+
| 2018-01-15 17:10:00 | 2018-01-15 17:14:59 | 0.201 | 1.002 |

最佳答案

编写一个子查询,获取每个组中的第一个和最后一个时间戳,然后将它们连接起来以获取相应的 startvendv

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

DEMO

对于 5 分钟的间隔,您应该除以 300,而不是 900(即 15 分钟)。

关于mysql - 分组为间隔多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48311248/

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