Skip to content

Instantly share code, notes, and snippets.

@muratgu
Created September 6, 2020 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muratgu/b5c4650739db45977b6c52f8152dd46d to your computer and use it in GitHub Desktop.
Save muratgu/b5c4650739db45977b6c52f8152dd46d to your computer and use it in GitHub Desktop.
WITH SourceData AS
(
SELECT
[MyColumn] AS ID, -- 1. The column containing the sequence
RowNum = ROW_NUMBER() OVER (ORDER BY [MyColumn])
FROM
dbo.[MyTable] -- 2. The table containing the column
),
Ranked AS
(
SELECT
*,
DENSE_RANK() OVER (ORDER BY ID - RowNum) As Series
FROM SourceData
),
Counted AS
(
SELECT
*,
COUNT(*) OVER (PARTITION BY Series) AS SCount
FROM Ranked
),
Gaps AS
(
SELECT
MinID = MIN(ID),
MaxID = MAX(ID),
Series
FROM
Counted
GROUP BY Series
)
SELECT
FirstNumberInGap = (a.MaxID + 1),
LastNumberInGap = (b.MinID - 1),
GapSize = ((b.MinID - 1) - a.MaxID)
FROM
Gaps a
INNER JOIN
Gaps b ON a.Series + 1 = b.Series
ORDER BY
FirstNumberInGap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment