1

我有 SQL,它输出日期时间戳行和状态更改标志(0 或 1)

我需要获取从第一个记录(标志为 0)到状态标志变为 1 的时间跨度,当标志仍为 1 时忽略记录,然后获取它变回 0 后的时间跨度直到最后的记录。状态改变标志可以在 0 和 1 之间翻转任意次数。

所以我需要能够将状态更改标志与前一行进行比较,并决定是否需要继续累积日期时间戳的差异。

我一直在研究写一个游标,但继续阅读游标是如何非常低效的。

希望这有任何意义。

4

2 回答 2

1
DECLARE @test TABLE ([group] int,t DateTime,[status] bit)

INSERT INTO @test values (1,'20130101 11:11:11',0)
INSERT INTO @test values (1,'20130101 11:11:12',0)
INSERT INTO @test values (1,'20130101 11:11:13',0)
INSERT INTO @test values (1,'20130101 11:11:14',1)
INSERT INTO @test values (1,'20130101 11:11:15',1)
INSERT INTO @test values (1,'20130101 11:11:16',1)
INSERT INTO @test values (1,'20130101 11:11:17',0)
INSERT INTO @test values (1,'20130101 11:11:18',0)
INSERT INTO @test values (1,'20130101 11:11:19',0)


Select [Group],MIN(t)

,(Select MAX(t) from @test t2 where [status]=0 and t2.[group]=t.[group] and Exists(Select * from @test t3 where [status]=1 and t3.[group]=t.[group] and  t3.t<t2.t))
,DateDiff(ss,MIN(t)
,(Select MAX(t) from @test t2 where [status]=0 and t2.[group]=t.[group] and Exists(Select * from @test t3 where [status]=1 and t3.[group]=t.[group] and  t3.t<t2.t))
) as Seconds
from @test t where Status=0
group by [group]
于 2013-04-08T14:17:04.680 回答
0

我认为这样的事情会奏效。但我可能需要更多关于表结构的信息

WITH FirstFlag(FlagType, FlagTime)
AS
(
    SELECT 
        FlagType
        , min(DateCreated) as FlagTime
    FROM TheTable
    WHERE Flag = 0
)
, SecondFlag(FlagTime1, FlagTime2)
AS
(
    SELECT 
        F.FlagTime as FlagTime
        , min(T.DateCreated) as FlagTime
    FROM TheTable as T
        INNER JOIN FirstFlag as F
            ON T.FlagType = F.FlagType
    WHERE Flag = 1
        AND T.DateCreated > F.FlagTime
)
SELECT datediff(min, FlagTime1, FlagTime2)
FROM SecondFlag
于 2013-04-08T14:20:03.080 回答