SQL Server SELECT LAST N Rows

前端 未结 18 2130
猫巷女王i
猫巷女王i 2020-11-28 03:13

This is a known question but the best solution I\'ve found is something like:

SELECT TOP N *
FROM MyTable
ORDER BY Id DESC

I\'ve a table wi

相关标签:
18条回答
  • 2020-11-28 03:42

    MS doesn't support LIMIT in t-sql. Most of the times i just get MAX(ID) and then subtract.

    select * from ORDERS where ID >(select MAX(ID)-10 from ORDERS)
    

    This will return less than 10 records when ID is not sequential.

    0 讨论(0)
  • 2020-11-28 03:43
    DECLARE @MYVAR  NVARCHAR(100)
    DECLARE @step  int
    SET @step = 0;
    
    
    DECLARE MYTESTCURSOR CURSOR
    DYNAMIC 
    FOR
    SELECT col FROM [dbo].[table]
    OPEN MYTESTCURSOR
    FETCH LAST FROM MYTESTCURSOR INTO @MYVAR
    print @MYVAR;
    
    
    WHILE @step < 10
    BEGIN   
        FETCH PRIOR FROM MYTESTCURSOR INTO @MYVAR
            print @MYVAR;
            SET @step = @step + 1;
    END   
    CLOSE MYTESTCURSOR
    DEALLOCATE MYTESTCURSOR
    
    0 讨论(0)
  • 2020-11-28 03:44

    You can do it by using the ROW NUMBER BY PARTITION Feature also. A great example can be found here:

    I am using the Orders table of the Northwind database... Now let us retrieve the Last 5 orders placed by Employee 5:

    SELECT ORDERID, CUSTOMERID, OrderDate
    FROM
    (
        SELECT ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY OrderDate DESC) AS OrderedDate,*
        FROM Orders
    ) as ordlist
    
    WHERE ordlist.EmployeeID = 5
    AND ordlist.OrderedDate <= 5
    
    0 讨论(0)
  • 2020-11-28 03:45

    Maybe a little late, but here is a simple select that solve your question.

    SELECT * FROM "TABLE" T ORDER BY "T.ID_TABLE" DESC LIMIT 5;
    
    0 讨论(0)
  • In a very general way and to support SQL server here is

    SELECT TOP(N) *
    FROM tbl_name
    ORDER BY tbl_id DESC
    

    and for the performance, it is not bad (less than one second for more than 10,000 records On Server machine)

    0 讨论(0)
  • 2020-11-28 03:49

    To display last 3 rows without using order by:

    select * from Lms_Books_Details where Book_Code not in 
     (select top((select COUNT(*) from Lms_Books_Details ) -3 ) book_code from Lms_Books_Details) 
    
    0 讨论(0)
提交回复
热议问题