SQL Server SELECT LAST N Rows

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

    First you most get record count from

     Declare @TableRowsCount Int
     select @TableRowsCount= COUNT(*) from <Your_Table>
    

    And then :

    In SQL Server 2012

    SELECT *
    FROM  <Your_Table> As L
    ORDER BY L.<your Field>
    OFFSET <@TableRowsCount-@N> ROWS
    FETCH NEXT @N ROWS ONLY;
    

    In SQL Server 2008

    SELECT *
    FROM 
    (
    SELECT ROW_NUMBER() OVER(ORDER BY ID) AS sequencenumber, *
    FROM  <Your_Table>
        Order By <your Field>
    ) AS TempTable
    WHERE sequencenumber > @TableRowsCount-@N 
    
    0 讨论(0)
  • 2020-11-28 03:53

    You can make SQL server to select last N rows using this SQL:

    select * from tbl_name order by id desc limit N;
    
    0 讨论(0)
  • 2020-11-28 03:53

    This query returns last N rows in correct order, but it's performance is poor

    select *
    from (
        select top N *
        from TableName t
        order by t.[Id] desc
    ) as temp
    order by temp.[Id]
    
    0 讨论(0)
  • 2020-11-28 03:55

    Is "Id" indexed? If not, that's an important thing to do (I suspect it is already indexed).

    Also, do you need to return ALL columns? You may be able to get a substantial improvement in speed if you only actually need a smaller subset of columns which can be FULLY catered for by the index on the ID column - e.g. if you have a NONCLUSTERED index on the Id column, with no other fields included in the index, then it would have to do a lookup on the clustered index to actually get the rest of the columns to return and that could be making up a lot of the cost of the query. If it's a CLUSTERED index, or a NONCLUSTERED index that includes all the other fields you want to return in the query, then you should be fine.

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

    Here's something you can try without an order by but I think it requires that each row is unique. N is the number of rows you want, L is the number of rows in the table.

    select * from tbl_name except select top L-N * from tbl_name
    

    As noted before, which rows are returned is undefined.

    EDIT: this is actually dog slow. Of no value really.

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

    Try using the EXCEPT syntax.
    Something like this:

       SELECT * 
        FROM   clientDetails 
        EXCEPT 
        (SELECT TOP (numbers of rows - how many rows you want) * 
         FROM   clientDetails) 
    
    0 讨论(0)
提交回复
热议问题