简体   繁体   中英

Find Missing multiple numbers sequence in SQL server

My table is like this:

DrawDate    num    DrawName    etc...
2015-08-01  2      Draw 2
2015-08-01  3      Draw 3
2015-08-02  1      Draw 1
2015-08-02  2      Draw 2
2015-08-02  4      Draw 4
2015-08-03  3      Draw 3
2015-08-04  1      Draw 1
2015-08-04  2      Draw 2
2015-08-04  3      Draw 3
2015-08-04  4      Draw 4

i would like to get the missing sequence number (num column) in the Table. How could i achieve this?

I had find so many solutions but there are drawbacks of not including start number or the hardcoding the first and last number for sequence. But i could not hardcode there any value. Start value is specified by 1 but no end sequence is defined. it could be 4 as in the table above or in some cases may be 18 or 20 but i need to find the duplicates by drawdate maximum value (the last one).

Edit

The Final Result would be

DrawDate    missingnum   
2015-08-01    1     
2015-08-02    3      
2015-08-03    1      
2015-08-03    2      

Let me guess:

declare @t table 
(
    DrawDate    date,
    Num         int
)

insert into @t values
('2015-08-01' ,  2 ),
('2015-08-01' ,  3 ),
('2015-08-02' ,  1 ),
('2015-08-02' ,  2 ),
('2015-08-02' ,  4 ),
('2015-08-03' ,  3 ),
('2015-08-04' ,  1 ),
('2015-08-04' ,  2 ),
('2015-08-04' ,  3 ),
('2015-08-04' ,  4 );


with AvailableDates as
(
    select distinct DrawDate from @t
),
AvailableNumbers as
(
    select distinct Num from @t
),
CrossJoined as
(
    select
        DrawDate,
        Num
    from    
        AvailableDates
        cross join AvailableNumbers
)
select
    *
from
    CrossJoined cj
    left join @t t on t.DrawDate = cj.DrawDate and t.Num = cj.Num
where
    t.Num is null;

Edit

The second guess (after the comment reading):

with MaxNumberPerDate as
(
    select DrawDate, MaxNum = max(Num) from @t group by DrawDate
),
N as 
(
    select n from (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) t(n)    
),
Multiplied as
(
    select
        DrawDate,
        Num     =   N.n
    from    
        MaxNumberPerDate md
        inner join N on N.n <= md.MaxNum
)
select
    m.*
from
    Multiplied m
    left join @t t on t.DrawDate = m.DrawDate and t.Num = m.Num
where
    t.Num is null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM