1

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

但是,这并没有给我想要的。请让我知道如何纠正此问题以满足我的要求。

4

3 回答 3

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
于 2013-07-23T20:05:27.450 回答
2

“mm”为您提供以月为单位的日期差异

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

将“毫米”替换为“分钟”

where DATEDIFF(minute,t1.recordDate,t2.recordDate)>15
于 2013-07-23T20:05:14.620 回答
1

也许就这么简单:

where ABS(DATEDIFF(minute,t1.recordDate,t2.recordDate))>15
于 2013-07-23T20:07:07.297 回答