2013-07-23 82 views
0

我正在使用SQL Server 2008,並且在編寫比較兩個連續記錄的查詢時需要幫助。試圖比較兩個連續記錄

select recordDate 
from SiteHistory 
where siteId = 556145 
    and isRecent = 0 
    and isRunning = 1 
order by 
    recordDate DESC 

給了我在2000年左右列,看起來像這樣:

recordDate 
----------------------- 
2013-05-08 20:04:23.357 
2013-05-08 19:45:26.417 
2013-05-08 19:30:24.810 
2013-05-08 19:17:22.843 
2013-05-08 19:00:16.017 
2013-05-08 18:44:14.230 
..... 
..... 

現在我需要每一行的日期與下一行比較並計算連續兩個日期之間的差多少次大於15分鐘。 這是我能想出迄今:

;with temp as(
select row_number()over(order by recordDate DESC)as 'row', recordDate 
from SiteHistory 
where siteId = 556145 and isRecent =0 and isRunning=1 
) 

select COUNT(*) as Count from temp t1 
INNER JOIN temp t2 ON t2.row = t1.row+1 
where DATEDIFF(mm,t1.recordDate,t2.recordDate)>15 

然而,這並沒有給我想要的。請讓我知道如何糾正這一點,以適應我的要求。

+1

什麼是實際輸出?另外,SQL Server是否具有'lag()'窗口功能? – 2013-07-23 19:53:59

+2

哪個版本的SQL Server?並且你沒有得到預期的結果?顯示演示所需角落案例的具體示例。 – MatBailie

+0

就像我剛纔提到的,我使用的是SQL Server 2008.如果您查看記錄,至少有幾條記錄,連續時間之間的差異大於15分鐘。所以我期待一個至少大於1的計數,但是我的計數是0. 據我所知,我不認爲SQL服務器具有lag()函數。 –

回答

2

查詢的邏輯是正確的,唯一的嘗試得到日期差異在月內將其更改爲分鐘

datediff(minute, t1.RecordDate, t2.RecordDate) > 15 

查詢:

;with temp as(
    select row_number()over(order by recordDate DESC)as 'row', recordDate 
    from SiteHistory 
    where siteId = 556145 and isRecent = 0 and isRunning = 1 
) 
    select COUNT(*) as Count from temp t1 
    INNER JOIN temp t2 ON t2.row = t1.row+1 
    where DATEDIFF(minute, t1.recordDate, t2.recordDate) > 15 
+0

你擊敗了我12秒! LOL –

+0

這其實只是測試數據。我最終必須將其改爲幾小時(HH)。我非常忙於試圖正確地理解邏輯,以致於不注意那些細節。謝謝。 –

2

「毫米」爲您提供了個月

where DATEDIFF(mm,t1.recordDate,t2.recordDate)>15 

日期差異與「分」替換爲「毫米」

where DATEDIFF(minute,t1.recordDate,t2.recordDate)>15 
+0

Sheesh!非常感謝! –

1

也許是這樣簡單:

where ABS(DATEDIFF(minute,t1.recordDate,t2.recordDate))>15 
+0

是的。我很迷茫,以至於毫不留情地投入。謝謝。 –