当前位置: 代码迷 >> Sql Server >> 请问怎么找到连续数据的最大号
  详细解决方案

请问怎么找到连续数据的最大号

热度:48   发布时间:2016-04-24 10:38:50.0
请教如何找到连续数据的最大号
如 数据库的编号已有如下 但是中间有缺号 想根据某个数字查找到连续的最大号
1
2
3
4
5
6
7
 <-  缺8
9
10
11
12
13
14
15
 <-  缺 16-17
18
19
20
21

输入 1-7 都应该找到7  
输入9-15 都应该找到 15 
输入18-21 应该找到21
------解决方案--------------------
借版主的生成例子数据的sql验证了一下,都正确:

declare @t table (f int)
 
insert into @t(f)
 select 1 union all
 select 2 union all
 select 3 union all
 select 4 union all
 select 5 union all
 select 6 union all
 select 7 union all
 select 9 union all
 select 10 union all
 select 11 union all
 select 12 union all
 select 13 union all
 select 14 union all
 select 15 union all
 select 18 union all
 select 19 union all
 select 20 union all
 select 21
 
declare @n int
set @n=1 --7,11,18
select top 1 * from (
select a.f,b.f x from @t a
left join @t b on a.f=b.f-1
) a
where f>@n and x is null
order by f
  相关解决方案