我有一堆产品订单,我试图按日期分组,并合计该日期的数量。我如何按月/日/年分组而不考虑时间部分?
3/8/2010 7:42:00应与3/8/2010 4:15:00归为一组
我有一堆产品订单,我试图按日期分组,并合计该日期的数量。我如何按月/日/年分组而不考虑时间部分?
3/8/2010 7:42:00应与3/8/2010 4:15:00归为一组
当前回答
CAST datetime字段到日期
select CAST(datetime_field as DATE), count(*) as count from table group by CAST(datetime_field as DATE);
其他回答
CAST datetime字段到日期
select CAST(datetime_field as DATE), count(*) as count from table group by CAST(datetime_field as DATE);
GROUP BY DATEADD(day, DATEDIFF(day, 0, MyDateTimeColumn), 0)
或者在SQL Server 2008以后,你可以像@Oded建议的那样简单地转换为Date:
GROUP BY CAST(orderDate AS DATE)
下面是我使用的一个例子,当我需要计算特定日期的记录数量而不包括时间部分时:
select count(convert(CHAR(10), dtcreatedate, 103) ),convert(char(10), dtcreatedate, 103)
FROM dbo.tbltobecounted
GROUP BY CONVERT(CHAR(10),dtcreatedate,103)
ORDER BY CONVERT(CHAR(10),dtcreatedate,103)
GROUP BY DATE(date_time_column)
在Sql 2008之前,通过去掉日期部分:
GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)