这里要说的是,你应该提供一个创建脚本:
declare @Table1 TABLE
([id] int, [time] time)
;
INSERT INTO @Table1
([id], [time])
VALUES
(1, '1:00 PM'),
(2, '1:02 PM'),
(3, '1:03 PM'),
(4, '1:05 PM'),
(5, '1:06 PM'),
(6, '1:09 PM'),
(7, '1:10 PM'),
(8, '1:12 PM'),
(9, '1:13 PM'),
(10, '1:15 PM')
;
我将与此查询做到这一点:
declare @interval int
set @interval = 5
;with next_times as(
select id, [time], (select min([time]) from @Table1 t2 where t2.[time] >= dateadd(minute, @interval, t1.[time])) as next_time
from @Table1 t1
),
t as(
select id, [time], next_time
from next_times t1 where id=1
union all
select t3.id, t3.[time], t3.next_time
from t inner join next_times t3
on t.next_time = t3.[time]
)
select id, [time] from t order by 1
-- results:
id time
----------- ----------------
1 13:00:00.0000000
4 13:05:00.0000000
7 13:10:00.0000000
10 13:15:00.0000000
(4 row(s) affected)
即使在间隔缺失的情况下也能正常工作:
-- delete the 1:05 PM record
delete from @table1 where id = 4;
;with next_times as(
select id, [time], (select min([time]) from @Table1 t2 where t2.[time] >= dateadd(minute, @interval, t1.[time])) as next_time
from @Table1 t1
),
t as(
select id, [time], next_time
from next_times t1 where id=1
union all
select t3.id, t3.[time], t3.next_time
from t inner join next_times t3
on t.next_time = t3.[time]
)
select id, [time] from t order by 1;
-- results:
id time
----------- ----------------
1 13:00:00.0000000
5 13:06:00.0000000
8 13:12:00.0000000
(3 row(s) affected)
这很棘手......期待看到的答案。 (只要它没有循环或光标) – SqlZim
这有什么用途?这听起来像一个[X Y问题](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)或Py/JS的工作 – scsimon