如何选择时间戳接近相邻行的行?

时间:2017-06-06 16:02:18

标签: sql-server sql-server-2008

我有一个SQL表,时间戳为一个字段。如何选择“相邻”行即。,时间戳在某个增量(例如 5秒)内的行?

编辑:

样本表:

CurrTime                Weight Length
----------------------- ------ -------------
2017-05-05 12:59:52.000 392    18.18
2017-05-05 12:59:29.000 396    18.18
2017-05-05 12:59:22.000 511    18.5
2017-05-05 12:58:53.000 512    18.5
2017-05-05 12:58:49.000 537    18.5

所以查询应该返回:

CurrTime                Weight Length
----------------------- ------ -------------
2017-05-05 12:58:53.000 512    18.5
2017-05-05 12:58:49.000 537    18.5

3 个答案:

答案 0 :(得分:3)

这样的事情......也可以用交叉应用来完成。

declare @table table (CurrTime datetime2)
insert into @table
values
('2017-05-05 12:59:52.000'),
('2017-05-05 12:59:29.000'),
('2017-05-05 12:59:22.000'),
('2017-05-05 12:58:53.000'),
('2017-05-05 12:58:49.000')

;with cte as(
select distinct
    t.CurrTime
    ,DATEDIFF(SECOND,t.CurrTime,t2.CurrTime) d
from 
    @table t
inner join
    @table t2 on
    t2.CurrTime <> t.CurrTime)

select * 
from cte 
where d <= 5 and d >= -5

对于交叉申请,只需通过d&lt;&gt;删除自引用。 0

;with cte as(
select distinct
    t.CurrTime
    ,DATEDIFF(SECOND,t.CurrTime,t2.CurrTime) d
from 
    @table t
    cross apply @table t2)

select * from cte 
where d <= 5 and d >= -5 and d <> 0

答案 1 :(得分:2)

使用exists()

select *
from t
where exists (
  select 1
  from t i
  where i.currtime<>t.currtime 
    and abs(datediff(second,i.currtime,t.currtime))<=5
    )

rextester演示:http://rextester.com/LYDBV65396

返回:

+-------------------------+--------+--------+
|        CurrTime         | Weight | Length |
+-------------------------+--------+--------+
| 2017-05-05 12:58:53.000 |    512 | 18.50  |
| 2017-05-05 12:58:49.000 |    537 | 18.50  |
+-------------------------+--------+--------+

答案 2 :(得分:0)

As far as I understand, you have an input datetime, and you want to find the rows within @delta value. You could use the below if that's the case:

DECLARE @datetime   DATETIME    = GETDATE() -- use your valid input date here.
DECLARE @delta      INT         = 5 -- delta in seconds

SELECT *
FROM    YourTable 
WHERE   CurrTime BETWEEN DATEADD(SECOND, -1 * @delta, @datetime) AND DATEADD(SECOND, @delta, @datetime)