Selecting Nth Record in an SQL Query

后端 未结 12 949
悲&欢浪女
悲&欢浪女 2020-12-28 23:33

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

L

12条回答
  •  情话喂你
    2020-12-28 23:48

    This is a classic interview question.

    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;
    

    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
    )
    

提交回复
热议问题