试图比较两个连续的记录

时间:2013-07-23 19:53:05

标签: sql sql-server sql-server-2008

我正在使用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

然而,这并没有给我所期望的。请让我知道如何根据我的要求纠正这个问题。

3 个答案:

答案 0 :(得分:3)

您的查询的逻辑是正确的,只有它试图获得月份的日期差异才能将其更改为

中的分钟
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

答案 1 :(得分:2)

“mm”为您提供

的日期差异
where DATEDIFF(mm,t1.recordDate,t2.recordDate)>15

将“mm”替换为“分钟”

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

答案 2 :(得分:1)

也许它就像这样简单:

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