时间:2021-07-01 10:21:17 帮助过:3人阅读
条件 【ID】
查询 【N】条
select * from [Table] where ID in (select top (【N】+1) ID from [Table] where id <=【ID】 order by id desc
union
select top 【N】 ID from [Table] where id>【ID】 order by id )
order by ID
例如:有数据表 A
id name datet
1 123123 2015-08-04 11:19:32.770
3 qwerqwer 2015-08-04 11:19:34.710
4 qwerqfsd 2015-08-04 11:19:35.507
7 jhndf 2015-08-04 11:19:38.507
8 sdfsdfc 2015-08-04 11:19:39.720
10 asdfsvc 2015-08-04 11:19:42.897
12 gdfvasdf 2015-08-04 11:19:44.927
13 vwrt4g 2015-08-04 11:19:46.517
15 asdvsdfg 2015-08-04 11:19:52.150
查询ID 为8的前后2条数据
SQL 语句为:
select * from A where ID in (select top 3 ID from A where id <=8 order by id desc
union
select top 2 ID from A where id>8 order by id )
order by ID
结果:
id name datet
4 qwerqfsd 2015-08-04 11:19:35.507
7 jhndf 2015-08-04 11:19:38.507
8 sdfsdfc 2015-08-04 11:19:39.720
10 asdfsvc 2015-08-04 11:19:42.897
12 gdfvasdf 2015-08-04 11:19:44.927
结束~~~~,大牛勿喷,主要记录一下,自己用。
Mssql 查询某记录前后N条
标签: