SQL Server GROUP BY datetime 忽略小时分钟以及带有日期和总和值的选择
我有一个包含两个字段的表 - datetime
和 int
。我只想对日期进行分组,忽略小时和分钟。 SELECT
语句应返回一个映射到一天的 int 总和的日期。
I have a table with two fields - datetime
and int
. I want to do a group by on the datetime
only on the date ignoring the hour and minute. The SELECT
statement should return a date that maps to the sum of the int of a single day.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于他没有指定他使用哪个版本的 SQL Server(
date
类型在 2005 年不可用),因此也可以使用As he didn't specify which version of SQL server he uses (
date
type isn't available in 2005), one could also use我来研究我必须这样做的选项,但是,我相信我使用的方法是最简单的:
I came researching the options that I would have to do this, however, I believe the method I use is the simplest:
-- 我喜欢这个,因为数据类型和格式与日期时间数据类型保持一致
-- I like this as the data type and the format remains consistent with a date time data type
就我个人而言,我更喜欢格式功能,它允许您非常轻松地更改日期部分。
Personally i prefer the format function, allows you to simply change the date part very easily.
对于 SQL Server 2022+,您可以使用
DATETRUNC
。与其他方法相比,它的优势在于它能够利用按
datetime
排序的索引也按date
排序的事实,并且可以避免排序操作。例如,比较下面的
For SQL Server 2022+ you can use
DATETRUNC
.This has an advantage over the other methods in that it is able to take advantage of the fact that an index ordered by
datetime
is also ordered bydate
and can avoid a sort operation.e.g. Compare the below