我正在使用 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
但是,这并没有给我想要的。请让我知道如何纠正此问题以满足我的要求。