Selecting Nth Record in an SQL Query

后端 未结 12 748
悲&欢浪女
悲&欢浪女 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:41
    Select from tablename limit nthrow,1;
    
    0 讨论(0)
  • 2020-12-28 23:44

    For SQL Server 2005:

    select rank() OVER (ORDER BY c.subject, c.date) as rank, c.subject, c.date
       from comments c
       where rank = 8
    
    0 讨论(0)
  • 2020-12-28 23:46
    select top 1 *
    from TableName
    where ColumnName1 in
    (
        select top nth ColumnName1
        from TableName
        order by ColumnName1 desc
    )
    order by ColumnName1 desc
    
    0 讨论(0)
  • 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
    )
    
    0 讨论(0)
  • 2020-12-28 23:51

    How about

    SELECT TOP 1 * FROM 
       (SELECT TOP 8 * FROM Comments ORDER BY foo ASC)
    ORDER BY foo DESC
    
    0 讨论(0)
  • 2020-12-28 23:51
    SELECT * FROM comments WHERE ...conditions... LIMIT 1 OFFSET 8
    

    OFFSET is a good thing for MySQL

    0 讨论(0)
提交回复
热议问题