gpt4 book ai didi

mysql - 按日期对 MYSQL 结果行进行分组

转载 作者:行者123 更新时间:2023-11-29 14:05:27 24 4
gpt4 key购买 nike

我想按时间戳的小时对从 MYSQL 数据库获取的结果进行分组。时间戳以 2012-12-14 03:19:09 格式存储在表中。我使用查询

SELECT
HOUR(`timestamp`) AS `hour`,
AVG(`somevalue`) AS `average`
FROM ...
GROUP BY
HOUR(`timestamp`),
DAY(`timestamp`),
MONTH(`timestamp`),
WEEK(`timestamp`),
YEAR(`timestamp`)
ORDER BY ...
LIMIT 0, 24;

这有效,并返回正确的行和值...

+------+-------+
| hour | value |
+------+-------+
| 13 | 21.16 |
| 12 | 21.11 |
| 11 | 20.88 |
| 10 | 20.93 |
| 9 | 20.87 |
| 8 | 20.89 |
| ... | ... |
+------+-------+

...但是速度非常慢(表包含约 90k 行)。我是given the advice不是按每个日期实体分组,而是按 UNIX_TIMESTAMP(`timestamp`)/3600 分组。不幸的是,这并没有达到预期的结果,结果看起来像这样

+------+-------+
| hour | value |
+------+-------+
| 13 | 21.20 |
| 13 | 21.20 |
| 13 | 21.20 |
| 13 | 21.20 |
| 13 | 21.20 |
| ... | ... |
+------+-------+

是否有任何方法可以仅通过一个组子句对它们进行分组(这将使其更快),但返回正确的结果?

最佳答案

不要使用按日期和时间分组

SELECT
HOUR(`timestamp`) AS `hour`,
AVG(`somevalue`) AS `average`
FROM ...
GROUP BY
DATE(`timestamp`),
HOUR(`timestamp`),
ORDER BY ...
LIMIT 0, 24;

关于mysql - 按日期对 MYSQL 结果行进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14424814/

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