SELECT Item, Line, MAX(sequence) maxSequence INTO #seqMax FROM SourceTable
Group by Item, Line
HAVING MAX(sequence) > COUNT(*) +1
--Although it can get same result without above HAVING condition, it improves performance for large amount data.
declare @max int
SELECT @max = maxSequence from #seqMax
declare @i int
create table #seqNum (sequence int)
SELECT @i =0
while @i <=@max
Begin
insert #seqNum values (@i)
set @i = @i +1
End
SELECT M.Item, M.Line, S.sequence
FROM #seqNum S JOIN #seqMax M ON S.sequence <= M.maxSequence
Left JOIN SourceTable I ON I.Item = M.Item AND I.Line = M.Line AND I.sequence = S.sequence
Where I.sequence IS NULL
ORDER BY M.Item, M.Line, S.sequence
Group by Item, Line
HAVING MAX(sequence) > COUNT(*) +1
--Although it can get same result without above HAVING condition, it improves performance for large amount data.
declare @max int
SELECT @max = maxSequence from #seqMax
declare @i int
create table #seqNum (sequence int)
SELECT @i =0
while @i <=@max
Begin
insert #seqNum values (@i)
set @i = @i +1
End
SELECT M.Item, M.Line, S.sequence
FROM #seqNum S JOIN #seqMax M ON S.sequence <= M.maxSequence
Left JOIN SourceTable I ON I.Item = M.Item AND I.Line = M.Line AND I.sequence = S.sequence
Where I.sequence IS NULL
ORDER BY M.Item, M.Line, S.sequence