用于查找第一个缺失序列字符串的SQL查询(前缀+否)

时间:2012-07-22 08:07:16

标签: sql sql-server

用于查找第一个缺失序列字符串(前缀+否)的T-SQL查询

序列可以有一个前缀+一个连续的否。

ex序列将是

ID
-------
AUTO_500
AUTO_501
AUTO_502
AUTO_504
AUTO_505
AUTO_506
AUTO_507
AUTO_508

因此,缺失序列的上方是AUTO_503,或者如果没有丢失序列,则必须返回下一个序列。

同样开始是指定ex。在这种情况下,500和前缀可以为空,即没有前缀仅作为序列的数字。

5 个答案:

答案 0 :(得分:4)

您可以LEFT JOIN移位(+1)值上的ID号来按顺序查找差距:

SELECT 
    MIN(a.offsetnum) AS first_missing_num
FROM 
(
    SELECT 500 AS offsetnum
    UNION
    SELECT CAST(REPLACE(id, 'AUTO_', '') AS INT) + 1
    FROM tbl
) a
LEFT JOIN
    (SELECT CAST(REPLACE(id, 'AUTO_', '') AS INT) AS idnum FROM tbl) b ON a.offsetnum = b.idnum
WHERE 
    a.offsetnum >= 500 AND b.idnum IS NULL

SQLFiddle Demo

答案 1 :(得分:3)

使用递归CTE动态生成ID号的最小值和最大值之间的序列可能有点复杂但有点似乎有效 -

LIVE ON FIDDLE

CREATE TABLE tbl (
  id VARCHAR(55)
);

INSERT INTO tbl VALUES 
('AUTO_500'),
('AUTO_501'),
('AUTO_502'),
('AUTO_504'),
('AUTO_505'),
('AUTO_506'),
('AUTO_507'),
('AUTO_508'),
('509');

;WITH 

  data_cte(id)AS
    (SELECT [id] = CAST(REPLACE(id, 'AUTO_', '') AS INT) FROM tbl)

  ,maxmin_cte(minId, maxId)AS
    (SELECT [minId] = min(id),[maxId] = max(id) FROM data_cte) 

  ,recursive_cte(n) AS 
  (
     SELECT [minId] n from maxmin_cte
     UNION ALL
     SELECT (1 + n) n FROM recursive_cte WHERE n < (SELECT [maxId] from maxmin_cte)
  )

SELECT x.n 
FROM 
     recursive_cte x
     LEFT OUTER JOIN data_cte y ON
        x.n = y.id
WHERE y.id IS NULL

答案 2 :(得分:1)

检查此解决方案。您只需添加标识列即可。

CREATE TABLE tbl (
      id VARCHAR(55),
      idn int identity(0,1)
    );

    INSERT INTO tbl VALUES
    ('AUTO_500'),
    ('AUTO_501'),
    ('AUTO_502'),
    ('AUTO_504'),
    ('AUTO_505'),
    ('AUTO_506'),
    ('AUTO_507'),
    ('AUTO_508'),
    ('509');

    SELECT min(idn+500) FROM tbl  where 'AUTO_'+cast((idn+500) as varchar)<>id

答案 3 :(得分:1)

试试这个:

with cte as(
select cast(REPLACE(id,'AUTO_','') as int)-500+1 [diff],ROW_NUMBER() 
over(order by cast(REPLACE(id,'AUTO_','') as int)) [rnk] from tbl)
select top 1 'AUTO_'+cast(500+rnk as varchar(50)) [ID] from cte 
where [diff]=[rnk] 
order by rnk desc

SQL FIddle Demo

答案 4 :(得分:0)

有类似的情况,我们有R_Cds就像这个R01005

;with Active_R_CD (R_CD)
As
(
Select Distinct Cast(Replace(R_CD,'R', ' ') as Int) 
from table
where stat = 1)

select Arc.R_CD + 1 as 'Gaps in R Code'
from Active_R_CD as Arc
  left outer join Active_R_CD as r on ARC.R_CD + 1 = R.R_CD
where R.R_CD is null
order by 1