我有SQL输出日期时间戳和状态更改标志(0或1)的行
我需要从第一个记录中获取时间跨度,其中标志将为0,当状态标志变为1时,忽略记录,当标志仍然为1时,然后获取时间跨度,在变换回到0到最后一个记录。状态更改标志可以在0到1之间翻转任意次数。
所以我需要能够将状态更改标记与上一行进行比较,并决定是否需要在日期时间戳中累积差异。
我一直在研究编写游标,但继续阅读游标的效率非常低。
希望这有任何意义。
答案 0 :(得分: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]
答案 1 :(得分: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