且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 SQL 查询中选择第 N 条记录

更新时间:2023-01-28 19:30:42

这是一道经典的面试题.

This is a classic interview question.

在 Ms SQL 2005+ 中,您可以使用 ROW_NUMBER() 关键字并具有谓词 ROW_NUMBER = n

In Ms SQL 2005+ you can use the ROW_NUMBER() keyword and have the Predicate ROW_NUMBER = n

USE AdventureWorks;
GO
WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
    FROM Sales.SalesOrderHeader 
)  

SELECT * 
FROM OrderedOrders 
WHERE RowNumber = 5;

在 SQL2000 中你可以做类似的事情

In SQL2000 you could do something like

SELECT Top 1 *FROM
[tblApplications]
where [ApplicationID] In
(
    SELECT TOP 5 [ApplicationID]
    FROM [dbo].[tblApplications]
    order by applicationId Desc
)