sql 查询记录数结果集某个区间内记录
更新时间:2012年11月29日 11:03:37 作者:
sqlserver如何实现查询记录数某个区间内记录,本文将提供多种解决方法,需要了解的朋友可以参考下
以查询前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时,整型列不能描述一个列,所以会产生非预期的效果. 待考虑下,有什么办法可以修改为想要的结果.
方法一: 先正查,再反查
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复制删除发布时遇到错误18752的问题及解决方法
朋友反馈他无法删除一台SQL Server数据库上的发布,具体情况为删除一个SQL Server Replication的发布时,遇到这样的错误问题如何解决呢,下面小编给大家分享SQL Server复制删除发布时遇到错误18752的问题及解决方法,感兴趣的朋友一起看看吧2024-01-01
SQL Server误区30日谈 第13天 在SQL Server 2000兼容模式下不能使用DMV
对于兼容模式已经存在了很多误解。80的兼容模式的数据库是否意味着能够附加或恢复到SQL Server 2000数据库?当然不是2013-01-01


最新评论