且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不排序的情况下选择表中的最后 5 行?

更新时间:2022-06-08 22:21:44

这几乎是我写过的最奇怪的查询,但我很确定它无需排序即可从表中获取最后 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.