SQL Server 选择最后 N 行 [英] SQL Server SELECT LAST N Rows

查看:63
本文介绍了SQL Server 选择最后 N 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个已知问题,但我找到的最佳解决方案如下:

This is a known question but the best solution I've found is something like:

SELECT TOP N *
FROM MyTable
ORDER BY Id DESC

我有一张有很多行的表.使用该查询是不可能的,因为它需要很多时间.那么如何在不使用 ORDER BY 的情况下选择最后 N 行?

I've a table with lots of rows. It is not a posibility to use that query because it takes lot of time. So how can I do to select last N rows without using ORDER BY?

编辑

抱歉重复了这个问题一个

推荐答案

您也可以使用 ROW NUMBER BY PARTITION 功能来实现.一个很好的例子可以在这里找到:

You can do it by using the ROW NUMBER BY PARTITION Feature also. A great example can be found here:

我正在使用 Northwind 数据库的 Orders 表...现在让我们检索员工 5 下的最后 5 个订单:

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

这篇关于SQL Server 选择最后 N 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆