2013-04-08 66 views
1

我有SQL其中輸出日期時間標記和狀態改變標誌的行(0或1)值到先前行的比較依賴於不同的領域

我需要從第一條記錄獲取時間跨度,標誌將爲0,狀態標誌變爲1時,忽略標誌爲1時的記錄,然後在變回0直到最後一條記錄後獲得時間跨度。狀態改變標誌可以在0和1之間任意次數翻轉。

所以我需要能夠比較狀態更改標誌與前一行,並決定是否需要不斷累積日期時間戳的差異。

我一直在尋找寫一個遊標,但不斷閱讀遊標是如何非常低效。

希望這是有道理的。

+0

如果您在SQL Server 2012上,可以使用'lag()'函數來訪問「previous」行中的值。 – 2013-04-08 14:32:00

+0

2005不幸:( – atamata 2013-04-08 15:33:33

回答

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] 
+0

謝謝,我只是試圖修改我自己的SQL,試圖讓這個工作 – atamata 2013-04-08 14:48:20

+0

似乎沒有算最後一行 – atamata 2013-04-08 15:49:03

+0

@atamata我做了一個編輯,沒有看到「..to 0直到最後..「 – bummi 2013-04-08 15:53:21

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 
+0

這實際上是與我上個月發佈的另一個問題 - http://stackoverflow.com/questions/15499675/denormalising-a-fully-normalised-表 – atamata 2013-04-08 14:48:47

+0

嗨,它實際上只是一個有兩個ID字段,日期時間戳和標誌的視圖。 – atamata 2013-04-08 15:40:44