首页 > 开发 > 综合 > 正文

Mssql 查询某记录前后N条

2024-07-21 02:46:13
字体:
来源:转载
供稿:网友
Mssql 查询某记录前后N条

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

结束~~~~,大牛勿喷,主要记录一下,自己用。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表