使用sql查找第n行

时间:2017-10-05 16:52:59

标签: sql sql-server

select top 20 * 
from dbo.DUTs D 
inner join dbo.Statuses S on d.StatusID = s.StatusID 
where s.Description = 'Active'

上面的SQL查询返回前20行,如何从上述查询的结果中获取第n行?我查看了之前关于找到第n行的帖子,并不清楚将它用于我的目的。

感谢。

4 个答案:

答案 0 :(得分:1)

行顺序是任意的,所以我会添加一个ORDER BY表达式。然后,你可以这样做:

SELECT TOP 1 * FROM (SELECT TOP 20 * FROM ... ORDER BY d.StatusID) AS d ORDER BY d.StatusID DESC

获得第20行。

您也可以使用OFFSET之类的:

SELECT * FROM ... ORDER BY d.StatusID OFFSET 19 ROWS FETCH NEXT 1 ROWS ONLY

还有第三种选择:

SELECT * FROM (SELECT *, rownum = ROW_NUMBER() OVER (ORDER BY d.StatusID) FROM ...) AS a WHERE rownum = 20

答案 1 :(得分:0)

我倾向于使用带有ROW_NUMBER()函数的CTE来按顺序编号。正如@zambonee所说,你需要一个ORDER BY子句,或者SQL每次都可以将它们放在不同的顺序中。它通常不会,但是如果没有自己订购,你不能保证两次获得同样的东西。这里我假设有一个[DateCreated]字段(DATETIME NOT NULL DEFAULT GETDATE()),这通常是一个好主意,所以你知道什么时候输入该记录。这说“给我那个表中的所有内容并添加一行,最新的记录为#1”:

; WITH AllDUTs
AS (
    SELECT  *
            , DateCreatedRank = ROW_NUMBER() OVER(ORDER BY [DateCreated] DESC)
    FROM    dbo.DUTs D
            INNER JOIN dbo.Statuses S ON D.StatusID = S.StatusID
    WHERE   S.Description = 'Active'
    )
SELECT *
FROM AllDUTs
WHERE AllDUTs.DateCreatedRank = 20;

答案 2 :(得分:0)

SELECT * FROM (SELECT * FROM EMP ORDER BY ROWID DESC) WHERE ROWNUM<11

答案 3 :(得分:0)

这是另一个样本:

SELECT * ,CASE WHEN COUNT(0)OVER() =ROW_NUMBER()OVER(ORDER BY number) THEN 1 ELSE 0 END IsNth
FROM ( 
    select top 10 * 
    from  master.dbo.spt_values AS d
    where d.type='P'
) AS t
+------+--------+------+-----+------+--------+-------+
| name | number | type | low | high | status | IsNth |
+------+--------+------+-----+------+--------+-------+
| NULL | 0      | P    | 1   | 1    | 0      | 0     |
| NULL | 1      | P    | 1   | 2    | 0      | 0     |
| NULL | 2      | P    | 1   | 4    | 0      | 0     |
| NULL | 3      | P    | 1   | 8    | 0      | 0     |
| NULL | 4      | P    | 1   | 16   | 0      | 0     |
| NULL | 5      | P    | 1   | 32   | 0      | 0     |
| NULL | 6      | P    | 1   | 64   | 0      | 0     |
| NULL | 7      | P    | 1   | 128  | 0      | 0     |
| NULL | 8      | P    | 2   | 1    | 0      | 0     |
| NULL | 9      | P    | 2   | 2    | 0      | 1     |
+------+--------+------+-----+------+--------+-------+