我有一个测试数据库,每个测试都有一个开始时间和(对于那些完成的)结束时间值。我想创建一个查询,该查询将显示每小时运行的测试数。
。
在任何给定的时间点具有开始时间但没有结束时间的测试。我解决了分组问题-感谢@p的回答。问题:SQL Server Group by Count of DateTime Per Hour?
您可以使用条件聚合:
SELECT CAST(StartDate as date) AS ForDate,
DATEPART(hour, StartDate) AS OnHour,
COUNT(*) AS TotalStarts,
SUM(CASE WHEN CAST(StartDate as date) <> CAST(EndDate as date) or
DATEPART(hour, StartDate) <> DATEPART(hour, EndDate)
THEN 1
ELSE 0
END) as StartedButNotEndedInHour
FROM #Events
GROUP BY CAST(StartDate as date),
DATEPART(hour,StartDate)