过滤指定时间两侧的设定时间段的时间值

Filter time values that are a set period either side of a specified time

给定指定的时间值和间隔值:

Specified Time: 13:25:00
Interval Value: 00:20:00

如何将以下 table 的值过滤到 return 倍,即 Specified 任一侧的指定 Interval时间.

12:45:24
13:05:00
13:50:30
14:50:32
15:15:10

我想要一个函数或查询来检查“13:25:00”是否与 table 中的任何时间有“00:20:00”差异。

输出应该return:

13:05:00

如果我们正确理解您的问题,您希望所有时间都比给定(特殊)时间长于 20 分钟。

要实现这一点,只需执行一个 select 和一个包含如下子句的 where 子句:abs(datediff(minute, tableDate, @specialdate)) > 20

SQLFiddle sample 和代码示例:

declare @specialDate datetime = '1900-01-01 13:25:00'

select *
  from SampleData
 where abs(datediff(minute, SomeDate, @specialDate)) > 20

请注意,我将 Datetime 列的日期设置为 1900-01-01 作为模糊参考,请根据您的设置进行调整。

您将需要行中的 ABS 以确保检查结果 datediff 的两个变体(它可以返回 0、> 0 或 < 0)

参考文献:
MSDN: DATEDIFF
MSDN: ABS

根据您提供的信息,我假设您想从列表中获取 "special time".

两侧指定时间段的值

这是使用 DATEADD 的一种方法:

-- temp table for your sample data
CREATE TABLE #times ( val TIME )

INSERT  INTO #times
        ( val )
VALUES  ( '12:45:24' ),
        ( '13:05:00' ),
        ( '13:50:30' ),
        ( '14:50:32' ),
        ( '15:15:10' )

DECLARE @special_time TIME = '13:25:00'      
DECLARE @diff_value TIME = '00:20:00'

-- variable will hold the total number of seconds for your interval
DECLARE @diff_in_seconds INT

-- gets the total number of seconds of your interval -> @diff_value 
SELECT  @diff_in_seconds = DATEPART(SECOND, @diff_value) + 60
        * DATEPART(MINUTE, @diff_value) + 3600 * DATEPART(HOUR, @diff_value)

-- get the values that match the criteria
SELECT  *
FROM    #times
WHERE   val = DATEADD(SECOND, @diff_in_seconds, @special_time)
        OR val = DATEADD(SECOND, -( @diff_in_seconds ), @special_time)

DROP TABLE #times

请注意,WHERE 子句通过加减差值来过滤结果。通过使 @diff_in_seconds 为负数来实现减法。

这是一个解决方案:

create table t(t time);

insert into t
values
    ('12:45:24'),
    ('13:05:00'),
    ('13:50:30'),
    ('14:50:32'),
    ('15:15:10')

declare @st time = '13:25:00'
declare @dt time = '00:20:00'

select * from t
where abs(datediff(ss, t, @st)) - datediff(ss, '00:00:00', @dt) = 0

abs(datediff(ss, t, @st) 将保持 table 和特殊时间之间的秒数差异。您将此差异与 00:00:00 和间隔 datediff(ss, '00:00:00', @dt)

之间的差异进行比较

输出:

t
13:05:00.0000000

Fiddle http://sqlfiddle.com/#!6/05df4/1