当前位置: 数据库>sqlserver
sql server中查询某个区间内数据的方法
来源: 互联网 发布时间:2014-08-29
本文导语: sql server中查询某个区间内数据的方法,有需要的朋友可以参考下。 以下内容以查询前20到30条为例,主键名为id。 方法一: 先正查,再反查 代码如下: select top 10 * from (select top 30 * from tablename order by id asc) A order by id desc 方法二...
sql server中查询某个区间内数据的方法,有需要的朋友可以参考下。
以下内容以查询前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
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)
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
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
(select rank() over(order by id asc) rk, id from tablename) T
where rk between 20 and 30
第五种方法看上去好像没有问题,查了下文档,当over()用于rank/row_number时,整型列不能描述一个列,所以会产生非预期的效果。