How to find a gap in range in SQL

这一生的挚爱 提交于 2019-12-11 01:34:51

问题


This question explains how to find the first "unused" number in a table, but how can I find the same so that I can define extra constraints. How do I alter the query so that I get the first unused number after that's greater than 100

e.g. If I have 23, 56, 100, 101, 103 in my table i should get 102.


回答1:


in mysql and postgresql

SELECT  id + 1
FROM    test mo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    test mi 
        WHERE   mi.id = mo.id + 1
        ) and mo.id> 100
ORDER BY
        id
LIMIT 1

fiddle for mysql and fiddle for postgresql

in ms sql

SELECT  TOP 1
        id + 1
FROM    test mo
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    test mi 
        WHERE   mi.id = mo.id + 1
        )
          and mo.id > 100
ORDER BY
        id

fiddle




回答2:


In Oracle Sql, you may try:

SELECT id
FROM
     (SELECT ID, lead(ID) OVER(ORDER BY ID) next_val FROM my_table t
     )
WHERE id +1 <> next_val
 AND id      >100;



回答3:


hope this will help you

SELECT MIN (id) + 1
  FROM myTable T1
 WHERE id >= 100
   AND NOT EXISTS (SELECT *
                     FROM myTable T2
                    WHERE T1.id + 1 = T2.id)



回答4:


Using generate_series() for fun & profit:

CREATE table islands (num INTEGER NOT NULL PRIMARY KEY);

INSERT INTO islands (num ) VALUES
(23), (56), (100), (101), (103) ;

WITH total AS (
        SELECT generate_series(mima.bot, mima.top) AS num
        FROM ( SELECT MIN(num) AS bot , MAX(num) AS top FROM islands) mima
        )
SELECT num
FROM total tt
WHERE num >=100
AND NOT EXISTS (
        SELECT *
        FROM islands ii
        WHERE ii.num = tt.num
        )
        ;



回答5:


use this:

SELECT TOP 1 a1.id + 1 FROM test a1 left JOIN test a2 
ON a1.id = a2.id - 1 
WHERE a2.id IS NULL AND a1.id > 100


来源:https://stackoverflow.com/questions/17782464/how-to-find-a-gap-in-range-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!