根据日期分组记录总数

时间:2012-09-10 15:53:44

标签: sql sql-server sql-server-2008 count group-by

在我的SqlServer 2008中,我有一个名为Table1的表,其中一列名为IncDate,这是一个DateTime。

我需要运行一个查询,该查询返回该日期之前的记录总数。例如,我的表有这些记录:

IncDate
09/09/2012 16:21:51.547
09/09/2012 16:22:11.032
10/09/2012 13:51:33.327

我的查询需要输出:

Date................Total
09/09/2012...........2 
10/09/2012...........1

3 个答案:

答案 0 :(得分:4)

您需要CAST()日期为仅限日期。

SELECT Cast(incdate as date) DateOnly, Count(*) AS Total
FROM yourtable
GROUP BY Cast(incdate as date)

请参阅SQL Fiddle with Demo

如果您没有CAST()迄今为止的日期,那么计数将会被取消。

答案 1 :(得分:0)

这是一种方式:

select cast(incdate as date) as date, count(*)
from table1
group by cast(incdate as date)
order by 1

答案 2 :(得分:0)

尝试

SELECT cast(incdate as [date]) as [idate], count(incdate) totalCount
FROM table1
GROUP BY cast(incdate as [date])
ORDER BY totalCount