码迷,mamicode.com
首页 > 数据库 > 详细

sql server选取第m行到第n行的元组

时间:2015-01-02 21:07:26      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

现在有一个表Questioin,主码是qid,要求选择第m行到第n行的元组

//方法一:效率最低

//错误:如果n<m,将选取前n条数据,如果n>=m,将选取从m+1开始的n条数据

select top n *
from Question
where qid not in
{
select top m qid
from Question
}

//当然改成下面的就正确了

select top(n-m)* 
from Question 
where qid not in
(select top m id from Question)

//方法二:先排序,据说效率最高

select top m * from 
(select top n * from Question order by qid asc)a
order by qid desc

//方法三:利用ROW_NUMBER函数对元组编号(推荐使用)

SELECT * FROM 
(
SELECT ROW_NUMBER() OVER(ORDER BY qid) as rowIndex,* FROM Question
)b
WHERE b.rowIndex>=m AND b.rowindex<=n

sql server选取第m行到第n行的元组

标签:

原文地址:http://www.cnblogs.com/yxr1993/p/4198791.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!