sql 查询记录数结果集某个区间内记录

所属分类: 数据库 / MsSql 阅读数: 392
收藏 0 赞 0 分享
以查询前20到30条为例,主键名为id

方法一: 先正查,再反查
select top 10 * from (select top 30 * from tablename order by id asc) A order by id desc

方法二: 使用left join
select top 10 A.* from tablename A
left outer join (select top 20 * from tablename order by id asc) B
on A.id = B.id
where B.id is null
order by A.id asc

方法三: 使用not exists
select top 10 * from tablename A
where id not exists
(select top 20 * from tablename B on A.id = B.id)

方法四: 使用not in
select top 10 * from tablename
where id not in
(select top 20 id from tablename order by id asc)
order by id asc

方法五: 使用rank()
select id from
(select rank() over(order by id asc) rk, id from tablename) T
where rk between 20 and 30

中第五种方法看上去好像没有问题,查了下文档,当over()用于rank/row_number时,整型列不能描述一个列,所以会产生非预期的效果. 待考虑下,有什么办法可以修改为想要的结果.
更多精彩内容其他人还在看

SQL SERVER的优化建议与方法

SQL SERVER的优化建议与方法
收藏 0 赞 0 分享

简单的SQL Server备份脚本代码

简单的SQL Server备份脚本代码
收藏 0 赞 0 分享

sql基本函数大全

sql基本函数大全
收藏 0 赞 0 分享

SQL查询语句精华使用简要第1/2页

SQL查询语句精华使用简要
收藏 0 赞 0 分享

数据库分页存储过程代码

数据库分页存储过程代码
收藏 0 赞 0 分享

SQL查询连续号码段的巧妙解法

SQL查询连续号码段的巧妙解法
收藏 0 赞 0 分享

sql server中千万数量级分页存储过程代码

sql server中千万数量级分页存储过程代码
收藏 0 赞 0 分享

sql2000各个版本区别总结第1/3页

sql2000各个版本区别总结
收藏 0 赞 0 分享

如何远程连接SQL Server数据库图文教程

如何远程连接SQL Server数据库图文教程
收藏 0 赞 0 分享

一个SQL语句获得某人参与的帖子及在该帖得分总和

一个SQL语句获得某人参与的帖子及在该帖得分总和
收藏 0 赞 0 分享
查看更多