2013-09-25 77 views
-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的序列號( 3,4)LNO的缺失尋找缺失序列的SQL Server

我需要找出失蹤的序列中沒有的爲clno

+0

請分享您在提問時已嘗試過的代碼。 – Robbert

回答

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

+0

Ok downvoter會很高興聽到你的解釋。是否因爲你不明白這個查詢在做什麼? :) –

+1

我不是downvoter,但似乎你並不是要求每個CNO的最大行數(假設它們不同),除了這應該被標記爲答案,有一個upvote – gh9

+0

@ gh9我沒有看到OP問題中對最大行數的任何要求,並且我的SQL給出了他想要的確切輸出 - 對於Cno 12從4到14以及對於Cno 13來說爲4和4.對於upvote :) –

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 

我不知道你在找什麼類型的輸出進行或如何你想選擇你正在尋找的缺失號碼。