当前位置: 代码迷 >> Sql Server >> 如何查询出断号前变的最后一条记录
  详细解决方案

如何查询出断号前变的最后一条记录

热度:64   发布时间:2016-04-24 09:04:37.0
怎么查询出断号前变的最后一条记录?
比如数据:1、2、3、9、10、11、15.....
我想查询到记录“3”。应该怎么写语句啊?
新人新手,请大家赐教!!!
------解决思路----------------------
;with data(id) as
(
select 1 union all
select 2 union all
select 3 union all
select 9 union all
select 10 union all
select 11 union all
select 15
)
, temp as
(
select *, rowNumber= ROW_NUMBER() over (order by id ) from data
)
select temp.id from temp
where rowNumber = (select min(rowNumber)-1 from temp where id <> rowNumber)


------解决思路----------------------
-- 借 1# 的一基础数据。
with data(id) as
(
select 1 union all
select 2 union all
select 3 union all
select 9 union all
select 10 union all
select 11 union all
select 15
)
select top 1 number -1  from (
select distinct number from master..spt_values where number > 0 
except 
select * from data 
) x 
------解决思路----------------------
--同样借用1楼的数据
--方法1
SELECT T1.id
FROM data T1
LEFT JOIN data T2 ON T1.id=T2.id-1
WHERE T2.id IS NULL
--方法2
SELECT T1.id
FROM data T1
WHERE NOT EXISTS(SELECT 1 FROM data T2 WHERE T1.id=T2.id-1)

------解决思路----------------------
create table #temp(id int)

insert into #temp
select 1 union all
select 2 union all
select 3 union all
select 9 union all
select 10 union all
select 11 union all
select 15


select min(orderId) as id
from (
select id,row_number() over(order by id) orderId
from #temp
) tab 
where id<>orderId

------解决思路----------------------
写错了,不过查出id=4,楼主你再查表,条件为id<4d的就行
------解决思路----------------------
with table1(id) as
(
select 1 union all
select 2 union all
select 3 union all
select 9 union all
select 10 union all
select 11 union all
select 15
)
select top 1 a.id 
from table1 a 
left join (select id - 1 id from table1) b on a.id=b.id where b.id is null

------解决思路----------------------
大神们,这样就直接COPY用吗
  相关解决方案