SQL TSQL从表中选择最后10行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6485609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TSQL to select the last 10 rows from a table?
提问by Contango
I have a table that contains 300 million rows, and a clustered index on the [DataDate] column.
我有一个包含 3 亿行的表,在 [DataDate] 列上有一个聚集索引。
How do I select the last 10 rows of this table (I want to find the most recent date in the table)?
如何选择此表的最后 10 行(我想在表中查找最近的日期)?
Database: Microsoft SQL Server 2008 R2.
数据库:Microsoft SQL Server 2008 R2。
Update
更新
The answers below work perfectly - but only if there is a clustered index on [DataDate]. The table is, after all, 300 million rows, and a naive query would end up taking hours to execute rather than seconds. The query plan is using the clustered index on [DataDate] to get results within a few tens of milliseconds.
下面的答案非常有效 - 但前提是 [DataDate] 上有聚集索引。毕竟,该表有 3 亿行,一个简单的查询最终会花费数小时而不是几秒钟来执行。查询计划使用 [DataDate] 上的聚集索引在几十毫秒内获得结果。
回答by Akram Shahda
TOP (Transact-SQL)specifies that only the first set of rows will be returned from the query result. The set of rows can be either a number or a percent of the rows. The TOP
expression can be used in SELECT
, INSERT
, UPDATE
, MERGE
, and DELETE
statements.
TOP (Transact-SQL)指定仅从查询结果中返回第一组行。行集可以是行的数字或百分比。的TOP
表达可以用在SELECT
,INSERT
,UPDATE
,MERGE
,和DELETE
语句。
SELECT TOP(10) *
FROM MyTable
ORDER BY DataDate DESC
回答by devuxer
Do a reverse sort using ORDER BY and use TOP.
使用 ORDER BY 进行反向排序并使用 TOP。