找出與某id相近的四條記錄

declare @tb table(id int,cName char(10))
insert into @tb
select 3,'aae' UNION ALL
select 5,'aBe' UNION ALL
select 6,'a89' UNION ALL
select 7,'b89' UNION ALL
select 10,'a22' UNION ALL
select 12,'B87' UNION ALL
select 13,'BHU' UNION ALL
select 14,'B22' UNION ALL
select 15,'aKI' UNION ALL
select 17,'a09'

--設id=7,找出與7最相近的四條記錄:5,6,7,10
--------------------------------------------------------
select top 4 * from @tb order by abs(7-id)

/*
id          cName     
----------- ----------
7           b89      
6           a89      
5           aBe      
10          a22      

(所影響的行數爲 4 行)
*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章