如何在不排序的情况下选择表中的最后 5 行?
问题描述:
我想从 SQL Server 中的一个表中选择最后 5 条记录,而不是按升序或降序排列该表.
I want to select the last 5 records from a table in SQL Server without arranging the table in ascending or descending order.
答
这几乎是我写过的最奇怪的查询,但我很确定它无需排序即可从表中获取最后 5"行:
This is just about the most bizarre query I've ever written, but I'm pretty sure it gets the "last 5" rows from a table without ordering:
select *
from issues
where issueid not in (
select top (
(select count(*) from issues) - 5
) issueid
from issues
)
请注意,这利用了 SQL Server 2005 将值传递到top"子句的能力 - 它不适用于 SQL Server 2000.
Note that this makes use of SQL Server 2005's ability to pass a value into the "top" clause - it doesn't work on SQL Server 2000.