SQL Server 2008 - 按顺序删除编号

时间:2018-01-11 07:06:56

标签: sql sql-server-2008 sequence

我看到了相关的问题,但我真的不明白该怎么做。

我有一个表名" tbl_image"

id       keys       image_count   
1        0001            1
2        0001            3
3        0001            5
4        0003            6
5        0003            9

我希望我的输出看起来像这样 如果我选择键=' 0001'

的位置
output
2
4

当我选择键=' 0003'

output
7
8

提前致谢。

3 个答案:

答案 0 :(得分:2)

一种方法是使用递归cte

;with cte as
(
    select id, image_count,min(image_count) over (partition by Keys) cm, keys from table
    union all
    select id, image_count, cm+1, keys from cte c
    where c.image_count > c.cm
)
select distinct c.cm as Missing from cte c
left join table t on t.keys = c.keys and t.image_count = c.cm
where c.keys = '0003' and t.image_count is null

结果:

Missing
7
8

答案 1 :(得分:0)

使用递归查询

with result as
(
   select min(image_count) + 1 output, 
          (select max(image_count) - 1 from tbl_image where keys = '0003') max_output
   from tbl_image 
   where keys = '0003'
   union all
   select output + 1, max_output
   from result
   where output < max_output
)
select output 
from result
where not exists (select 1 from tbl_image where image_count = output)

dbfiddle demo

答案 2 :(得分:0)

试试这个:

DECLARE @tbl_image TABLE(ID int, Keys VARCHAR(10),Image_Count INT)
INSERT INTO @tbl_image VALUES (1,'0001',1)
INSERT INTO @tbl_image VALUES (2,'0001',3)
INSERT INTO @tbl_image VALUES (3,'0001',5)
INSERT INTO @tbl_image VALUES (4,'0003',6)
INSERT INTO @tbl_image VALUES (5,'0003',9)

SELECT DISTINCT n = number 
FROM Master.dbo.[spt_values] 
WHERE number BETWEEN (SELECT MIN(Image_Count) FROM @tbl_image WHERE Keys='0001') 
    AND (SELECT MAX(Image_Count) FROM @tbl_image WHERE Keys='0001')
    AND number NOT IN(SELECT Image_Count FROM @tbl_image WHERE Keys='0001')

<强>输出:

2
4