SQL Server Group by Count of DateTime Per Hour?
How about this? Assuming SQL Server 2008:
SELECT CAST(StartDate as date) AS ForDate,
DATEPART(hour,StartDate) AS OnHour,
COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
DATEPART(hour,StartDate)
For pre-2008:
SELECT DATEADD(day,datediff(day,0,StartDate),0) AS ForDate,
DATEPART(hour,StartDate) AS OnHour,
COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
DATEPART(hour,StartDate)
This results in :
ForDate | OnHour | Totals
-----------------------------------------
2011-08-09 00:00:00.000 12 3
Alternatively, just GROUP BY
the hour and day:
SELECT CAST(Startdate as DATE) as 'StartDate',
CAST(DATEPART(Hour, StartDate) as varchar) + ':00' as 'Hour',
COUNT(*) as 'Ct'
FROM #Events
GROUP BY CAST(Startdate as DATE), DATEPART(Hour, StartDate)
ORDER BY CAST(Startdate as DATE) ASC
output:
StartDate Hour Ct
2007-01-01 0:00 3
2007-01-02 5:00 2
2007-01-03 4:00 1
2007-01-07 3:00 1
I found this somewhere else. I like this answer!
SELECT [Hourly], COUNT(*) as [Count]
FROM
(SELECT dateadd(hh, datediff(hh, '20010101', [date_created]), '20010101') as [Hourly]
FROM table) idat
GROUP BY [Hourly]