SQL Server 按每小时日期时间计数进行分组?
create table #Events
(
EventID int identity primary key,
StartDate datetime not null,
EndDate datetime not null
)
go
insert into #Events (StartDate, EndDate)
select '2007-01-01 12:44:12 AM', '2007-01-01 12:45:34 AM' union all
select '2007-01-01 12:45:12 AM', '2007-01-01 12:46:34 AM' union all
select '2007-01-01 12:46:12 AM', '2007-01-01 12:47:34 AM' union all
select '2007-01-02 5:01:08 AM', '2007-01-02 5:05:37 AM' union all
select '2007-01-02 5:50:08 AM', '2007-01-02 5:55:59 AM' union all
select '2007-01-03 4:34:12 AM', '2007-01-03 4:55:18 AM' union all
select '2007-01-07 3:12:23 AM', '2007-01-07 3:52:25 AM'
(向 http://www 致歉.sqlteam.com/article/working-with-time-spans-and-durations-in-sql-server 用于收获他们的基本sql)
我试图找到一小时内发生的事件的计数,所以结果集看起来像这个:
2007-01-01 12:00 3
2007-01-02 5:00 2
2007-01-03 4:00 1
2007-01-07 3:00 1
我一直在玩 dateadd 和 round 和 grouping,但没有得到它。有人可以帮忙吗?
谢谢。
create table #Events
(
EventID int identity primary key,
StartDate datetime not null,
EndDate datetime not null
)
go
insert into #Events (StartDate, EndDate)
select '2007-01-01 12:44:12 AM', '2007-01-01 12:45:34 AM' union all
select '2007-01-01 12:45:12 AM', '2007-01-01 12:46:34 AM' union all
select '2007-01-01 12:46:12 AM', '2007-01-01 12:47:34 AM' union all
select '2007-01-02 5:01:08 AM', '2007-01-02 5:05:37 AM' union all
select '2007-01-02 5:50:08 AM', '2007-01-02 5:55:59 AM' union all
select '2007-01-03 4:34:12 AM', '2007-01-03 4:55:18 AM' union all
select '2007-01-07 3:12:23 AM', '2007-01-07 3:52:25 AM'
(with apologies to http://www.sqlteam.com/article/working-with-time-spans-and-durations-in-sql-server for harvesting their base sql)
I am trying to find the count of Events that occurred in an hour, so the result set would look like this:
2007-01-01 12:00 3
2007-01-02 5:00 2
2007-01-03 4:00 1
2007-01-07 3:00 1
I have been playing with dateadd and round and grouping but not getting it. Can anyone help?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个怎么样?假设 SQL Server 2008:
对于 2008 之前版本:
这会导致:
How about this? Assuming SQL Server 2008:
For pre-2008:
This results in :
或者,只需按小时和日期进行分组:
输出:
Alternatively, just
GROUP BY
the hour and day:output:
我在其他地方找到了这个。我喜欢这个答案!
I found this somewhere else. I like this answer!
您还可以通过使用以下 SQL 将日期和时间放在同一列中并使用正确的日期时间格式并按日期时间排序来实现此目的
You can also achieve this by using following SQL with date and hour in same columns and proper date time format and ordered by date time