用sql语句查询没有连续的字段 如 字段内容为 1,2,3,5,8,11 则输出 4,6,7,9

2025-02-23 18:47:57
推荐回答(1个)
回答1:

思路:

  1. 构建字段序列, 如 从1到11的序列;

  2. 查询缺失的序列;

--基础数据
with tmp as 
(select 1 as id   union all 
select 2   union all 
select 3   union all 
select 5   union all 
select 8   union all 
select 11  ),
--构建序列
tmp1 (s_id,e_id) as
(select min(id),max(id) from tmp 
union all
select s_id+1,e_id from tmp1
where s_id--查询缺失的序列
select s_id from tmp1 where s_id not in (select id from tmp)
order by s_id;