-3
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 缺少的序列号

4

2 回答 2

0

您可以使用公用表表达式来生成数字范围,然后找到缺失的数字:

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

于 2013-09-25T17:35:30.740 回答
0

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

如果您有一个名为 numbers 的表,如下所示:

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

我不知道您正在寻找什么类型的输出或您想如何选择您正在寻找的缺失数字。

于 2013-09-25T17:38:17.020 回答