我看了很多其他的问题,没有什么比我的问题更合适或得到我需要的答案,也许我今天只是很慢:(
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存在连续失败(Status = 4)。因此对于上述InstructionDetailId 113和114将是连续失败,因为它们的[Sequence]是3和4,对于InstructionDetailId 118和119将是连续失败。我已经尝试了这么多的行数变化和cte's,我不能完全解决它:(这是适用于SQL Server 2008 R2的方式。
预期产量:
InstructionId InstructionDetailId Sequence Status
222 113 3 4
222 114 4 4
222 118 8 4
222 119 9 4
谢谢大家!
你可以使用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);
也许最简单的方法是使用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;
你能做点什么......
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