Alternate of lead lag function in SQL Server 2008

后端 未结 3 643
孤城傲影
孤城傲影 2020-12-01 21:37

I want to compare the current row with a value in the next row. SQL has LEAD and LAG functions to get the next and previous values but I can not us

3条回答
  •  一个人的身影
    2020-12-01 22:24

    In your case, the ids appear to be numeric, you can just do a self-join:

    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;
    

    This isn't quite the same minute. It is within 60 seconds. Do you actually need the same calendar time minute? If so, you can do:

    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);
    

提交回复
热议问题