MySql 查询按时间分组
我正在尝试创建一份报告来了解下订单的时间,因此我需要按时间对它们进行求和和分组。例如,我想要计算 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果幸运的是它是 mysql 并且订单总和指的是订单数量而不是价值金额:
If by luck it is mysql and by sum of orders you mean the number of orders and not the value amount:
这种分组之王(使用计算字段)肯定不会随着时间的推移而扩展。如果您确实需要频繁执行这个特定的 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.