查找缺少的序列SQL Server

时间:2013-09-25 17:28:37

标签: sql sql-server

CNo Wno Lno
12  1    1
12  1    2
12  2    3
12  3    15
9   1    1
13  1    1
13  2    2
13  3    5
10  1    1
10  1    2
10  1    3
10  2    4
11  1    1

对于Cno我需要Lno中缺少的序列号 例如: 对于Cn0 = 12 从4到14缺少一行 并且对于Cno = 13,Lno的序列号(3,4)缺失

我需要找出clno缺少的序列号

2 个答案:

答案 0 :(得分:0)

您可以使用common table expression生成数字范围,然后找到丢失的数字:

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

答案 1 :(得分:0)

不是100%确定你要做什么,但你可以使用数字表来帮助解决这个问题。

如果您有一个名为这样的数字的表:

number 
  1
  2
  3
  4
  5.. up to highest number you are interested in

然后你可以做类似的事情:

select 
    n.number
from
    numbers as n
    left outer join table as t
        on n.number = t.Lno
        and t.cno = 12
where
    n.number <= (select max(lno) from table where cno = 12)
    and t.nco is null

我不知道您正在寻找什么类型的输出,或者您想要如何选择所需的丢失数字。