How do I select last 5 rows in a table without sor

2019-01-07 13:25发布

I want to select the last 5 records from a table in SQL Server without arranging the table in ascending or descending order.

20条回答
三岁会撩人
2楼-- · 2019-01-07 14:03

You can retrieve them from memory.
So first you get the rows in a DataSet, and then get the last 5 out of the DataSet.

查看更多
Bombasti
3楼-- · 2019-01-07 14:03
select * 
from table 
order by empno(primary key) desc 
fetch first 5 rows only
查看更多
成全新的幸福
4楼-- · 2019-01-07 14:04
select * from table limit 5 offset (select count(*) from table) - 5;
查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-07 14:04

In SQL Server 2012 you can do this :

Declare @Count1 int ;

Select @Count1 = Count(*)
FROM    [Log] AS L

SELECT  
   *
FROM    [Log] AS L
ORDER BY L.id
OFFSET @Count - 5 ROWS
FETCH NEXT 5 ROWS ONLY;
查看更多
冷血范
6楼-- · 2019-01-07 14:04

Get the count of that table

select count(*) from TABLE
select top count * from TABLE where 'primary key row' NOT IN (select top (count-5) 'primary key row' from TABLE)
查看更多
Viruses.
7楼-- · 2019-01-07 14:07

There is a handy trick that works in some databases for ordering in database order,

SELECT * FROM TableName ORDER BY true

Apparently, this can work in conjunction with any of the other suggestions posted here to leave the results in "order they came out of the database" order, which in some databases, is the order they were last modified in.

查看更多
登录 后发表回答