2017-06-06 68 views
2

我有一個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 
+1

這裏需要更多一點的信息。 ..請分享一些示例數據和期望的結果。並分享您迄今爲止嘗試過的任何內容。 – Siyual

+0

@Siyual添加示例 – Conrad

+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

存在的完美用例。 +1 – scsimon

+0

@scsimon謝謝!我也是這麼想。 – SqlZim

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刪除自參考<> 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 
0

據我瞭解,你有一個輸入日期時間,並且要@delta值內找到行。你可以使用,如果是這樣的情況下,如下所示:

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)