sql >> Base de Datos >  >> RDS >> Sqlserver

¿Grupo de SQL Server por conteo de fecha y hora por hora?

¿Qué tal esto? Asumiendo 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)

Para antes de 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)

Esto da como resultado:

ForDate                 | OnHour | Totals
-----------------------------------------
2011-08-09 00:00:00.000     12       3