日期:2014-05-16  浏览次数:20389 次

如何按照时间段分组数据
本帖最后由 icecard1 于 2014-04-22 15:48:58 编辑
数据库sql server 2012.
有一张表EmailHistory,记录了邮件发送的时间:
Id        sentTime      
1          1:00:01
2          1:00:02
3          1:00:03
4          1:00:05
5          1:00:16
6          1:00:17
7          1:00:19
8          1:00:25
9          1:00:29
10       1:00:42
11        1:00:43
12        1:00:47
.........

当同一时刻有许多邮件需要发送时,邮件会进入服务器队列依次发送,上表中sentTime记录了发送的时间。
通俗点说,邮件都是一波一波的来,我需要通过查询了解每一波邮件的情况。判断的标准是:每相邻两封邮件发送时间间隔不超过10秒。
上表中,1~4行算一波 (4、5行之间时间超过11秒),5~9行算第2波(9、10行间隔13秒),10~12行算第3波。期望结果如下:
Id        sentTime      bo
1          1:00:01         1
2          1:00:02         1
3          1:00:03         1
4          1:00:05         1
5          1:00:16         2
6          1:00:17         2
7          1:00:19         2
8          1:00:25         2
9          1:00:29         2
10       1:00:42         3
11        1:00:43         3
12        1:00:47         3
.........

数据量较大,我不希望使用游标或循环。Sql server 2012 有很多分析函数和窗口函数,像lead, first_value之类都能很接近实现,但始终不能达到上面的效果。请教大家,怎么写这个查询语句呢?


------解决方案--------------------
use tempdb
go
if OBJECT_ID('tb') is not null drop table tb
go
create table tb(
id int
,val varchar(100)
,g int
)
insert into tb(id,val)
select '1','1:00:01'
union all select '2','1:00:02'
union all select '3','1:00:03'
union all select '4','1:00:05'
union all select '5','1:00:16'
union all select '6','1:00:17'
union all select '7','1:00:19'
union all select '8','1:00:25'
union all select '9','1:00:29'
union all sele