SQL Server 2008中的前导滞后功能的替代

Mah*_*344 11 sql sql-server sql-server-2008

我想将当前行与下一行中的值进行比较.SQL有LEADLAG函数来获取下一个和以前的值,但我不能使用它们,因为我使用的是SQL Server 2008.

那我怎么得到这个?

我有输出表

+----+-------+-----------+-------------------------+
| Id | ActId |  StatusId |       MinStartTime      |
+----+-------+-----------+-------------------------+
| 1  |  42   | 1         | 2014-02-14 11:17:21.203 |
| 2  |  42   | 1         | 2014-02-14 11:50:19.367 |
| 3  |  42   | 1         | 2014-02-14 11:50:19.380 |
| 4  |  42   | 6         | 2014-02-17 05:25:57.280 |
| 5  |  42   | 6         | 2014-02-19 06:09:33.150 |
| 6  |  42   | 1         | 2014-02-19 06:11:24.393 |
| 7  |  42   | 6         | 2014-02-19 06:11:24.410 |
| 8  |  42   | 8         | 2014-02-19 06:44:47.070 |
+----+-------+-----------+-------------------------+
Run Code Online (Sandbox Code Playgroud)

我想要做的是,如果当前行状态为1并且下一行状态为6并且两个时间相同(最多几分钟),那么我想获得状态为1的行.

例如:Id 6行具有状态1而Id 7行具有状态6但两个时间相同即.2014-02-19 06:11

所以我想得到状态1的这行或id,即.id 6

Gor*_*off 11

在你的情况下,ids看起来是数字,你可以只做一个自我加入:

select t.*
from table t join
     table tnext
     on t.id = tnext.id - 1 and
        t.StatusId = 1 and
        tnext.StatusId = 6 and
        datediff(second, t.MinStartTime, tnext.MinStartTime) < 60;
Run Code Online (Sandbox Code Playgroud)

这不是完全相同的一分钟.它在60秒内.你真的需要相同的日历时间分钟吗?如果是这样,你可以这样做:

select t.*
from table t join
     table tnext
     on t.id = tnext.id - 1 and
        t.StatusId = 1 and
        tnext.StatusId = 6 and
        datediff(second, t.MinStartTime, tnext.MinStartTime) < 60 and
        datepart(minute, t.MinStartTime) = datepart(minute, tnext.MinStartTime);
Run Code Online (Sandbox Code Playgroud)