在 SQL 查询中选择第 N 条记录 [英] Selecting Nth Record in an SQL Query
问题描述
我有一个正在运行的 SQL 查询,但我只想选择特定的行.例如,假设我的查询是:
I have an SQL Query that i'm running but I only want to select a specific row. For example lets say my query was:
Select * from Comments
假设这返回 10 行,我只想选择此查询返回的第 8 条记录.我知道我可以做到:
Lets say this returns 10 rows, I only want to select the 8th record returned by this query. I know I can do:
Select Top 5 * from Comments
要获取该查询的前 5 条记录,但我只想选择某条记录,是否可以在此查询中添加任何内容(类似于 top).
To get the top 5 records of that query but I only want to select a certain record, is there anything I can put into this query to do that (similar to top).
谢谢
杰克
推荐答案
这是一道经典的面试题.
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
)
这篇关于在 SQL 查询中选择第 N 条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!