SQL Server GROUP BYdate时间忽略小时分钟,并select一个date和总和值

我有一个表有两个字段 – datetimeint 。 我想在datetime只在忽略小时和分钟的date做一个小组。 SELECT语句应该返回映射到一天的int的总和的date。

 SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField FROM MyTable GROUP BY CAST(Datetimefield AS DATE) 

由于他没有指定他使用哪个版本的SQL服务器( datetypes在2005年不可用),所以也可以使用

 SELECT CONVERT(VARCHAR(10),date_column,112),SUM(num_col) AS summed FROM table_name GROUP BY CONVERT(VARCHAR(10),date_column,112) 

我来研究的选项,我将不得不这样做,但是,我相信我使用的方法是最简单的:

 SELECT COUNT(*), DATEADD(dd, DATEDIFF(dd, 0, date_field),0) as dtgroup FROM TABLE GROUP BY DATEADD(dd, DATEDIFF(dd, 0, date_field),0) ORDER BY dtgroup ASC; 

– 我喜欢这种数据types,格式与date时间数据types保持一致

 ;with cte as( select cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts from dbo.mytable cd where utcdate between '2014-01-14' and '2014-01-15' group by cast(utcdate as date), DATEPART(hour, utcdate) ) select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts from cte