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

时间:2011-05-13 14:21:07

标签: sql-server-2005 tsql

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

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

理想情况下,我想获得一份清单 [block1-start block1-end] [block2-start block2-end] 等

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

Oracle为此提供了许多出色的分析功能。

我认为你需要做的是从sql语句创建一个游标,它将按Date,StartTime,EndTime命令你的结果。

答案 2 :(得分:1)

可以像这样使用带日期输入的表来获取登录之间的时间......

如果你的桌子上已有一个身份,请忽略ROW_NUMBER位。

{select 
    Start.ID
    ,Done.ID
    ,Start.<Date_Column>
    ,Done.<Date_Column>
    ,DATEDIFF(s,Start.<Date_Column>,Done.<Date_Column>) AS InBetween
from 
    (SELECT
        ROW_NUMBER() OVER (ORDER BY <Date_Column>) AS ID
        ,<Date_Column>
    FROM
        <Tablename> (NOLOCK)
    ) START
    INNER JOIN (
        SELECT
            ROW_NUMBER() OVER (ORDER BY <Date_Column>) AS ID
            ,<Date_Column>
        FROM
            <Tablename> (NOLOCK)
        ) DONE  ON START.ID + 1 = DONE.ID
ORDER BY
    DATEDIFF(s,Start.<Date_Column>,Done.<Date_Column>)DESC}