簡體   English   中英

SQL Server查找連續失敗記錄

[英]SQL Server find consecutive failure records

我看了很多其他問題,但沒有一個完全適合我的問題,也無法為我提供所需的答案,也許我今天很慢:(

DECLARE @t TABLE (
    [InstructionId] INT,
    [InstructionDetailId] INT,
    [Sequence] INT,
    [Status] INT
 ) 
 INSERT INTO @t SELECT 222,111,1, 2
 INSERT INTO @t SELECT 222,112,2,2
 INSERT INTO @t SELECT 222,113,3,4
 INSERT INTO @t SELECT 222,114,4,4
 INSERT INTO @t SELECT 222,115,5,2
 INSERT INTO @t SELECT 222,116,6,4
 INSERT INTO @t SELECT 222,117,7,2
 INSERT INTO @t SELECT 222,118,8,4
 INSERT INTO @t SELECT 222,119,9,4
 INSERT INTO @t SELECT 222,120,10,2
 INSERT INTO @t SELECT 222,121,11,2

我需要使用[Sequence]字段檢查順序以確定它們是否連續,以查找哪些InstructionDetailId連續失敗(狀態= 4)。 因此,對於上面的InstructionDetailId 113和114,它們將是連續失敗,因為它們的[Sequence]為3和4,對於InstructionDetailId 118和119,它們將是連續失敗。 我已經嘗試了很多行號變化和cte,但我還不太明白:(順便說一下,這是針對SQL Server 2008 R2的。

預期產量:

InstructionId   InstructionDetailId Sequence    Status
222                            113       3           4
222                            114       4           4
222                            118       8           4
222                            119       9           4

謝謝大家!

也許最簡單的方法是使用lag()lead()

select t.*
from (select t.*,
             lag(t.status) over (partition by t.InstructionId order by t.sequence) as prev_status,
             lead(t.status) over (partition by t.InstructionId order by t.sequence) as next_status
      from @t t
     ) t
where status = prev_status or status = next_status;

您可以使用APPLY

select t.*
from @t t outer apply
     ( select top (1) t1.*
       from @t t1
       where t1.InstructionId = t.InstructionId and
             t1.Sequence < t.Sequence
       order by t1.Sequence desc
     ) t1 outer apply
     ( select top (1) t2.*
       from @t t2
       where t2.InstructionId = t.InstructionId and
             t2.Sequence > t.Sequence
       order by t2.Sequence 
     ) t2
where t.status = 4 and (t.status = t1.status or t.status = t2.status);

你能做點什么...

    select t1.InstructionID,
           t1.InstructionDetailID,
           t1.Sequence,
           t1.Status,
      from @t t1
     inner join @t t2 on t1.InstructionID = t2.InstructionID
                     and t1.Sequence = (t2.Sequence - 1)
                     and t1.Status = t2.Status
                     and t1.Status = 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM