序列号记录的SQL范围得到剩余号

时间:2016-10-18 03:32:27

标签: sql sql-server

MSSQL Server 8.0
主表:

BATCHNo  SEQFrom  SEQTo   
0001    0001    3000  
0001    3000    5000  
0002    0001    0500 

表:

RecordID  BATCHNo  SEQFrom  SEQTo   
1      0001    0001    0100  
2      0001    0102    0202  
3      0001    0210    0222 

我想知道丢失的数字(101,203,204,205,206,207,208,209)
输出:

BATCHNo  SEQ   
0001   101
0001   203
0001   204
0001   205
0001   206
0001   207
0001   208
0001   209

1 个答案:

答案 0 :(得分:1)

MsSQL 2012+的解决方案如下:

DECLARE @Tbl TABLE (RecordID INT, BATCHNo VARCHAR(10), SEQFrom VARCHAR(10), SEQTo VARCHAR(10))
INSERT INTO @Tbl        
VALUES
(1,'0001', '0001','0100'),  
(2,'0001', '0102','0202'),  
(3,'0001', '0210','0222') 

;WITH Tally
AS
(
    SELECT 
        ones.n + 10 * tens.n + 100 * hundreds.n + 1000 * thousands.n AS Number,
        T.BATCHNo
    FROM 
        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n),
        (SELECT DISTINCT BATCHNo FROM @Tbl) T
    WHERE 
        ones.n + 10 * tens.n + 100 * hundreds.n + 1000 * thousands.n < (SELECT MAX(T.SEQTo * 1) FROM @Tbl T)

), Tmp
AS
(
    SELECT  
        *,
        LEAD(T.SEQFrom) OVER (ORDER BY RecordID) NextSEQ
    FROM @Tbl T

)

SELECT
    A.BATCHNo,
    B.Number AS SEQ
FROM 
    Tmp A INNER JOIN 
    Tally B ON B.Number > A.SEQTo AND B.Number < A.NextSEQ AND A.BATCHNo = B.BATCHNo

结果:

BATCHNo    SEQ
---------- -----------
0001       101
0001       203
0001       204
0001       205
0001       206
0001       207
0001       208
0001       209