views:

1068

answers:

2

i have a table of IDs and positions

CREATE TABLE #MissingSequence (ID INT NOT NULL, Position INT NOT NULL)
INSERT INTO #MissingSequence (ID,Position)
SELECT 36,1
UNION ALL SELECT 36,2
UNION ALL SELECT 36,3
UNION ALL SELECT 36,4
UNION ALL SELECT 36,5
UNION ALL SELECT 36,6
UNION ALL SELECT 44,1
UNION ALL SELECT 44,3
UNION ALL SELECT 44,4
UNION ALL SELECT 44,5
UNION ALL SELECT 44,6

What I am trying to find is if there is any break in the sequence of Positions by ID in this case the break between 44,1 and 44,3

I've managed to parse together:

SELECT  l.ID
    ,Start_Position = MIN(l.Position) + 1
    ,Stop_Position = MIN(fr.Position) - 1
FROM #MissingSequence l
LEFT JOIN #MissingSequence r 
    ON l.Position = r.Position - 1
LEFT JOIN #MissingSequence fr 
    ON l.Position < fr.Position
WHERE r.Position IS NULL
    AND fr.Position IS NOT NULL
GROUP BY l.ID

but it doesn't work if there are multiple ID values. It does work if only a single ID, 44 exists.

thoughts, comments, suggestions?

thanks!

+1  A: 

This query spots the slips, hope to be useful; if you are in SQL 2005, you can use a CTE

SELECT ID, Position + 1
FROM #MissingSequence t1
WHERE (Position + 1) NOT IN (SELECT Position FROM #MissingSequence t2 WHERE t1.ID = t2.ID)
AND Position <> (SELECT MAX(Position) FROM #MissingSequence t2 WHERE t1.ID = t2.ID)
Jhonny D. Cano -Leftware-
Won't this only detect single missing Position values, not runs of them?
bobince
ah ok, fine, sure
Jhonny D. Cano -Leftware-
+4  A: 

The left self-join was a good instinct, but I don't think the aggregates are going to cut it, and certainly you'd need to include the matching-ID clause in your self-joins.

Here's an (ANSI-compliant) version using the null-left-join idea, selecting a top row and a bottom row and checking there's nothing between them:

SELECT
    above.ID AS ID, below.Position+1 AS Start_Position, above.Position-1 AS End_Position
FROM MissingSequence AS above
JOIN MissingSequence AS below
    ON below.ID=above.ID AND below.Position<above.Position-1
LEFT JOIN MissingSequence AS inbetween
    ON inbetween.ID=below.ID AND inbetween.Position BETWEEN below.Position+1 AND above.Position-1
WHERE inbetween.ID IS NULL;

+----+----------------+--------------+
| ID | Start_Position | End_Position |
+----+----------------+--------------+
| 44 |              2 |            2 | 
+----+----------------+--------------+
bobince
I think this is just about it... the HAVING is being annoying but it's better than what I've come up with, thanks +1 [x]
SomeMiscGuy
Oh! Of course, you can do it without the HAVING. Updated query above; should perform a bit better, too.
bobince
awesome, that nailed it!
SomeMiscGuy