加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 09:55:52 所属栏目:MsSql教程 来源:网络整理
导读:以查询前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 tablenam

以查询前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时,整型列不能描述一个列,所以会产生非预期的效果. 待考虑下,有什么办法可以修改为想要的结果.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读