您可以使用公用表表达式来生成数字范围,然后找到缺失的数字:
with cte as (
select t.CNo, min(t.Lno) as Lno, max(t.Lno) as max_Lno from Table1 as t
group by t.CNo
union all
select c.CNo, c.Lno + 1 as Lno, c.max_Lno
from cte as c
where c.Lno < c.max_Lno
)
select c.Cno, c.Lno
from cte as c
where
not exists (
select *
from Table1 as t
where t.CNo = c.CNo and t.Lno = c.Lno
)
order by 1, 2
option (maxrecursion 0);
如果您有带有序号的表格,您可以这样做:
select c.Cno, n.n as Lno
from numbers as n
inner join (
select
tt.CNo, min(tt.Lno) as min_Lno, max(tt.Lno) as max_Lno
from Table1 as tt
group by tt.CNo
) as c on c.min_Lno <= n.n and c.max_Lno >= n.n
where
not exists (
select *
from Table1 as t
where t.CNo = c.CNo and t.Lno = n.n
)
order by 1, 2;
sql fiddle demo