SQL Server SELECT LAST N Rows

前端 未结 18 2252
猫巷女王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: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
    

提交回复
热议问题