2013-07-23 84 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

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