MySql 查询按时间分组

发布于 2024-10-27 15:16:08 字数 173 浏览 1 评论 0原文

我正在尝试创建一份报告来了解下订单的时间,因此我需要按时间对它们进行求和和分组。例如,我想要计算 1 到 1:59 之间所有订单的总和,然后下一行列出 2:00 到 2:59 之间所有订单的总和,等等。该字段是一个日期时间变量,但对于我一直无法找到正确的查询来执行此操作。任何让我走上正确道路的建议将不胜感激。

谢谢

I am trying to create a report to understand the time-of-day that orders are being placed, so I need to sum and group them by time. For example, I would like a sum of all orders placed between 1 and 1:59, then the next row listing the sum of all orders between 2:00 and 2:59, etc. The field is a datetime variable, but for the life me I haven't been able to find the right query to do this. Any suggestions sending me down the right path would be greatly appreciated.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风启觞 2024-11-03 15:16:08

如果幸运的是它是 mysql 并且订单总和指的是订单数量而不是价值金额:

select date_format(date_field, '%Y-%m-%d %H') as the_hour, count(*)
from my_table
group by the_hour
order by the_hour

If by luck it is mysql and by sum of orders you mean the number of orders and not the value amount:

select date_format(date_field, '%Y-%m-%d %H') as the_hour, count(*)
from my_table
group by the_hour
order by the_hour
甜柠檬 2024-11-03 15:16:08

这种分组之王(使用计算字段)肯定不会随着时间的推移而扩展。如果您确实需要频繁执行这个特定的 GROUP BY/ORDER BY,您应该创建一个额外的字段(一个 UNSIGNED TINYINT 字段就足够了)来存储小时,并在该列上放置一个 INDEX。

当然,如果您的表变得相当大,如果它很小(这不能仅用记录数量来表示,因为这实际上也是服务器配置和功能的问题),您可能不会注意到性能上有太大差异。

This king of grouping (using a calculated field) will certainly not scale over time. If you really need to execute this specific GROUP BY/ORDER BY frequently, you should create an extra field (an UNSIGNED TINYINT field will suffice) storing the hour and place an INDEX on that column.

That is of course if your table is becoming quite big, if it is small (which cannot be stated in mere number of records because it is actually a matter of server configuration and capabilities as well) you won't probably notice much difference in performance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文