查询以识别时间数据中的间隙

Cur*_*tis 1 t-sql sql-server-2005

我对数据库编程很陌生,而且我需要一些帮助来编写一个看似复杂的t-sql查询.

我们的数据库存储时间数据以及当时记录的各种级别.典型的测量将持续数周或数月.我需要在SqlServer2005中编写一个查询来识别时间数据中的间隙,以便知道仪器何时不通信.我们的采样间隔可以是1秒或0.5秒,但在给定的测量中它总是相同的(即:测量中的所有样本将是1或.5样本/秒).

理想情况下,我想获得[block1-start block1-end] [block2-start block2-end]等列表

其中每个块是整个测量中连续时间的单位.

TSQL中是否有任何命令可以使查询更容易?

Kei*_*ith 5

看一下这个.由于您没有重叠间隔,因此可以编写一个简单的SQL查询来返回这些结果.下面的SQL创建一个名为@Events的虚拟表变量来模拟您的测量表.最终查询输出大于1秒的间隙(可通过变量@MaxIntervalAllowedBetweenEvents配置).

-- table with dummy data
declare @Events table (
    ID          int IDENTITY NOT NULL,
    StartDate   datetime NOT NULL,
    EndDate     datetime NOT NULL
)
INSERT @Events VALUES ('1/1/2011 1:00am', '1/1/2011 2:00am')
INSERT @Events VALUES ('1/1/2011 2:00am', '1/1/2011 3:00am')  -- no gap after previous event
INSERT @Events VALUES ('1/1/2011 3:01am', '1/1/2011 4:00am')  -- 1 minute gap
INSERT @Events VALUES ('1/1/2011 4:30am', '1/1/2011 5:00am')  -- 30 minute gap


-- this variable defines the maximum interval allowed between events
declare @MaxIntervalAllowedBetweenEvents int
set @MaxIntervalAllowedBetweenEvents = 1    -- # seconds


-- select the gaps between events
SELECT
    e1.EndDate,
    Min(e2.StartDate) as NextEventStartDate,
    DateDiff(s, e1.EndDate, Min(e2.StartDate)) as SecondsBetweenEvents
FROM
    @Events as e1
join
    -- for each event in e1, get the event that immediately follows it
    @Events as e2
        on  (e1.EndDate <= e2.StartDate)
GROUP BY
    e1.EndDate
HAVING
    -- filter out events that are too close to each other
    (DateDiff(s, e1.EndDate, Min(e2.StartDate)) > @MaxIntervalAllowedBetweenEvents)
ORDER BY
    e1.EndDate
Run Code Online (Sandbox Code Playgroud)