Sqlserver 查询指定记录前后N条,包括当前数据
条件 【ID】
查询 【N】条
select * from [Table] where ID in (select top (【N】+1) ID from[Table] where id <=【ID】 order by id descunionselect top 【N】 ID from[Table] where id>【ID】 order by id )order by ID
例如:有数据表 A
id name datet1 123123 2015-08-04 11:19:32.7703 qwerqwer 2015-08-04 11:19:34.7104 qwerqfsd 2015-08-04 11:19:35.5077 jhndf 2015-08-04 11:19:38.5078 sdfsdfc 2015-08-04 11:19:39.72010 asdfsvc 2015-08-04 11:19:42.89712 gdfvasdf 2015-08-04 11:19:44.92713 vwrt4g 2015-08-04 11:19:46.51715 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 descunionselect top 2 ID from A where id>8 order by id )order by ID
结果:
id name datet4 qwerqfsd 2015-08-04 11:19:35.5077 jhndf 2015-08-04 11:19:38.5078 sdfsdfc 2015-08-04 11:19:39.72010 asdfsvc 2015-08-04 11:19:42.89712 gdfvasdf 2015-08-04 11:19:44.927
结束~~~~,大牛勿喷,主要记录一下,自己用。
新闻热点
疑难解答