我有一堆产品订单,我试图按日期分组,并合计该日期的数量。我如何按月/日/年分组而不考虑时间部分?

3/8/2010 7:42:00应与3/8/2010 4:15:00归为一组


当前回答

好吧,对我来说,它几乎是直接的,我使用cast和groupby:

例子:

Select cast(created_at as date), count(1) from dbname.tablename GROUP BY cast(created_at as date)

注意:我在MSSQL 2016上使用这个。

其他回答

GROUP BY DATE(date_time_column)

GROUP BY DATEADD(day, DATEDIFF(day, 0, MyDateTimeColumn), 0)

或者在SQL Server 2008以后,你可以像@Oded建议的那样简单地转换为Date:

GROUP BY CAST(orderDate AS DATE)

好吧,对我来说,它几乎是直接的,我使用cast和groupby:

例子:

Select cast(created_at as date), count(1) from dbname.tablename GROUP BY cast(created_at as date)

注意:我在MSSQL 2016上使用这个。

将值转换为组的日期类型。

GROUP BY CAST(myDateTime AS DATE)

在Sql 2008之前,通过去掉日期部分:

GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)