Get Gaps in a SQL Sequence

3

Hello, I have a select today that returns the following result:

I make another select that returns a value, 5 for example. I would need to know which numbers are not between the number 1 to the number 5. In my case I would need the following result 2, 4, 5.

I would need help developing this logic.

    
asked by anonymous 20.12.2018 / 17:05

1 answer

3

You can use the WITH clause to generate the number sequence and compare it with the table in question:

WITH sequencias
  AS (SELECT 1 AS sequencia
      UNION ALL
      SELECT s.sequencia + 1 AS sequencia
        FROM sequencias s
       WHERE s.sequencia <= 5)
SELECT s.*
  FROM sequencias s
 WHERE NOT EXISTS(SELECT 1
                    FROM tabela t
                   WHERE t.nr_volume = s.sequencia)
 ORDER BY s.sequencia
OPTION(MAXRECURSION 0);

We have a great explanation of the WITH command in the question answer Using WITH AS command on Sql Server .

    
20.12.2018 / 17:11