这听起来很简单,但我找不到任何答案。 我正在尝试按一天中的每个小时的时间运行查询。因此,我正在Group By按小时进行操作,但并非所有小时都具有数据,因此存在一些差距。我想每小时显示一次,无论是否有数据。
Group By
这是一个示例查询:
SELECT DATEPART(HOUR, DATEADD(HH,-5, CreationDate)) As Hour, COUNT(*) AS Count FROM Comments WHERE UserId = ##UserId## GROUP BY DATEPART(HOUR, DATEADD(HH,-5, CreationDate))
我的想法是联接到一个已经有1到24的表,以便将传入的数据放在该位置。
我可以通过CTE做到这一点吗?
WITH Hours AS ( SELECT i As Hour --Not Sure on this FROM [1,2,3...24]), --Not Sure on this CommentTimes AS ( SELECT DATEPART(HOUR, DATEADD(HH,-5, CreationDate)) AS Hour, COUNT(*) AS Count FROM Comments WHERE UserId = ##UserId## GROUP BY DATEPART(HOUR, DATEADD(HH,-5, CreationDate)) ) SELECT h.Hour, c.Count FROM Hours h JOIN CommentTimes c ON h.Hour = c.Hour
Explorer](https://data.stackexchange.com/stackoverflow/revision/185460/239532/comments- by- hour)的示例查询
您可以使用递归查询来构建所需数字的表。我们在这里停止在24点。然后将其与您的评论保持联系,以确保每个小时都有代表。如果需要,您可以轻松地将它们转变为时代。我还更改了您对hour列名的使用,因为它是一个关键字。
hour
;with dayHours as ( select 1 as HourValue union all select hourvalue + 1 from dayHours where hourValue < 24 ) , CommentTimes As ( SELECT DATEPART(HOUR, DATEADD(HH,-5, CreationDate)) As HourValue, COUNT(*) AS Count FROM Comments WHERE UserId = ##UserId## GROUP BY DATEPART(HOUR, DATEADD(HH,-5, CreationDate))) SELECT h.Hour, c.Count FROM dayHours h left JOIN CommentTimes c ON h.HourValue = c.HourValue