类似于TOP 10的查询选择中间记录?

时间:2009-04-27 05:55:03

标签: sql sql-server sql-server-2005

我有100条记录,我可以使用查询中的“TOP 10”选择前10名。同样有什么可以获得20到30的记录?

2 个答案:

答案 0 :(得分:3)

由于您使用的是SQL Server 2005,因此可以使用“new”ROW_NUMBER()函数。这将为您提供第11至20行:

SELECT  Description, Date
FROM     (SELECT  ROW_NUMBER() OVER (ORDER BY Date DESC)
             AS Row, Description, Date FROM LOG)
            AS LogWithRowNumbers
WHERE  Row >= 11 AND Row <= 20

如果你有很多记录,在内部SELECT子句中使用TOP X可能会加速一些事情,因为如果你只想抓取11到20的记录,就没有用来返回1000条记录:

SELECT  Description, Date
FROM     (SELECT TOP 20 ROW_NUMBER() OVER (ORDER BY Date DESC)
             AS Row, Description, Date FROM LOG)
            AS LogWithRowNumbers
WHERE  Row >= 11 AND Row <= 20

Source

答案 1 :(得分:1)

您应该使用ROWNUMBER()获取结果集的记录数,并在原因中过滤它。

SELECT * FROM   (SELECT ROW_NUMBER() OVER(ORDER BY name) AS
rownum, name , age FROM Table) AS Table1
WHERE rownum >= 2 AND rownum <= 5

----------------------------
rownum     | name |   age   |
----------------------------
   2     |John    |   25    | 
   3     |Adam    |   23    | 
   4     |Tom     |   19    |
   5     |Jame    |   22    |
----------------------------