使用sql获取数字列表之间缺少的数字

时间:2017-02-15 12:40:13

标签: sql sql-server

在我的数据库中我有10个用户号码,其中一些号码已被删除,当我在这样的节目中选择列时:

missing_user_number:
        1,
        2,
        5,
        8,
        10,

我需要知道是否有一个脚本能够得到这样的缺失数字,我不希望删除已删除的数据,我只想将缺失的数字作为整合数据:

missing_user_number:
        3,
        4,
        6,
        7,
        9,

2 个答案:

答案 0 :(得分:5)

在大多数SQL版本中,实际上更容易获得缺失值的范围,而不是每个缺失值:

select user_number + 1 as missing_range_start, next_user_number - 1 as missing_range_end
from (select t.*,
             lead(user_number) over (order by user_number) as next_user_number
      from t
     ) t
where user_number <> user_number + 1;

注意:这只会找到内部缺失的数字,如问题中的示例所示。

答案 1 :(得分:0)

您可以创建包含所有10个用户号码的内联号码表。然后LEFT JOIN你的桌子就可以得到丢失的数字:

SELECT t1.n AS missing_user_number
FROM (
   SELECT 1 AS n UNION ALL SELECT 2 ... SELECT 10  
) AS t1
LEFT JOIN mytable AS t2 ON t1.n = t2.user_number
WHERE t2.user_number IS NULL