以查詢前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時,整型列不能描述一個列,所以會產生非預期的效果. 待考慮下,有什麼辦法可以修改為想要的結果.