2016-08-11 58 views
0

我有一個查詢它返回一個確切的時間跨度:SQL - 修改查詢,以便從時間的間隔得到的值,而不是一個固定的時間

SELECT ScanDate FROM tTimes WHERE personId = 5 

的值,例如可以:

2016-08-10 16:26:42.000 

使用下面的查詢:

SELECT executedTime FROM tTimetable as tc 
WHERE tc.lastExecutedTime IN (SELECT ScanDate FROM tTimes WHERE personId =5) 

我會得到:

SELECT executedTime FROM tTimetable as tc 
    WHERE tc.lastExecutedTime IN (2016-08-10 16:26:42.000) 

不過,我想從

SELECT executedTime FROM tTimetable as tc 
     WHERE tc.lastExecutedTime IN (between 2016-08-10 16:16:42.000 and 2016-08-10 16:36:42.000)So everything which is between the `2016-08-10 16:26:42.000-10sec` and `2016-08-10 16:26:42.000+10secs` 

獲取值我怎樣才能archieve這樣的結果?

+0

添加一些樣本表數據和預期的結果。 – jarlh

+0

備註:您應該避免[日期和時間類型]的「BETWEEN」和包含上限(http://sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/what-do-between-and -the-devil-have-in-common.aspx),特別是在SQL Server上。 –

回答

3

如果我明白你的問題

SELECT executedTime 
    FROM tTimetable as tc 
    Join (
     Select DateR1 = DateAdd(SECOND,-10,ScanDate) 
       ,DateR2 = DateAdd(SECOND,10,ScanDate) 
     FROM tTimes WHERE personId = 5 
     ) B 
    on tc.lastExecutedTime between DateR1 and DateR2 
+0

這似乎是我閱讀這個問題的正確答案。我不知道爲什麼會被低估。 –

+0

@GordonLinoff我只需要一點時間來收集我自己...有所有更好 –

+0

嗯,也許是因爲[不應該在日期/時間類型中使用'BETWEEN'](http://sqlblog.com/blogs /aaron_bertrand/archive/2011/10/19/what-do-between-and-the-devil-have-in-common.aspx)? (不是downvoter,但它有可能使結果糟糕)結束時間應始終是排他性的,特別是對於這樣的範圍查詢。 –

1

我會用exists接近這樣的:

SELECT executedTime 
FROM tTimetable as tc 
WHERE EXISTS (SELECT 1 
       FROM tTimes 
       WHERE personId = 5 AND 
        tc.lastExecutedTime BETWEEN DATEADD(second, -10, ScanDate) AND DATEADD(second, 10, ScanDate) 
      ); 
+0

語法:DATEADD(-10,second ... –

+0

_Please_ [不要使用'BETWEEN'](http://sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/what-do-between-和-the-devil-have-in-common.aspx),尤其是在處理範圍時。想象一下使用bucketing會發生什麼! –

+0

@ Clockwork-Muse ...我之間使用'between',因爲OP之間使用,但是你有好點子。 –