|
这听起来很简单,但我找不到答案。
4 U7 D: }8 [. }% v5 n7 V4 s我试着在一天中每小时查询。所以,我在GroupBy按小时操作,但不是所有小时都有数据,所以有一些差距。我想每小时显示一次,不管有没有数据。
- d) u3 a" {' u; r# H; Z: _这是一个示例查询:
* ?5 S6 c( N& z2 i) b! H6 ]8 B9 pSELECT DATEPART(HOUR,DATEADD(HH,-5,CreationDate)) As Hour, COUNT(*) AS CountFROM CommentsWHERE UserId = ##UserId##GROUP BY DATEPART(HOUR,DATEADD(HH,-5,CreationDate))我的想法是把已经有1到24的表连接起来,把传入的数据放在这个位置。" R/ K* q# v: _4 N# Z3 m
我可以通过CTE这样做吗?) d, B) E; L& z3 L
WITH Hours AS ( SELECT i As Hour --Not Sure on this FROM [1,2,3...24]),--Not Sure on thisCommentTimes 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.CountFROM Hours hJOIN CommentTimes c ON h.Hour = c.Hour这是[来自Stack Exchange DataExplorer](https://data.stackexchange.com/stackoverflow/revision/185460/239532/comments-
. j# }4 S( Z' e+ w9 vby-8 @9 q2 j! I1 p" P: _
hour)的示例查询3 ]3 y7 [% _/ D
8 F2 C Q2 d0 M) N4 O3 B) ?$ ]" I
解决方案: 8 J' P: ~% Y& _9 b" t: l% @8 i1 A8 T
您可以使用递归查询来构建所需的数字表。我们在这里停在24点。然后联系你的评论,确保每小时都有代表性。如果有必要,你可以很容易地把它们变成时代。我也改变了你的观点hour使用列名,因为它是一个关键字。
; f! X8 |4 X7 _5 W;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.CountFROM dayHours hleft JOIN CommentTimes c ON h.HourValue = c.HourValue |
|