记录基于时差

时间:2017-03-09 20:16:30

标签: tsql

我有一个非常奇怪的要求。我试图创建一个SQL语句来执行此操作。我知道我可以创建一个游标但是试图看看它是否可以完成SQL

这是我的源数据。

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

我试图创建一个函数,如果我传递一个间隔,它将返回结果数据集。

例如我通过5分钟,然后我想要的记录是记录1,4,7和& 10。

有没有办法在SQL中执行此操作。注意:如果记录4(1:05 PM在数据集中没有,我希望看到1,5和8。我会看到5,因为它是下一个记录,时间大于5分钟记录1和记录8,因为它是记录5中时间大于5分钟的下一记录。

1 个答案:

答案 0 :(得分:3)

以下是您应该提供的创建脚本:

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)