Select Top N Records Ordered by X, But Have Results in Reverse Order

一曲冷凌霜 提交于 2019-12-04 03:21:41

问题


I'm trying to get the top N records (when ordered by some column X), but have the result set in reverse order. The following statement is incorrect, but probably demonstrates what I'm after:

SELECT * FROM (SELECT TOP 10 * FROM FooTable ORDER BY X DESC) ORDER BY X ASC

For example, column X could be an ID or a timestamp; I want the latest 10 records but want them returned in forward chronological order.


回答1:


SELECT * FROM 
   (SELECT TOP 10 * FROM FooTable ORDER BY X DESC) as myAlias 
ORDER BY X ASC 

i.e. you might need an alias on your subquery, but other than that it should work.




回答2:


Try

SELECT * FROM 
(SELECT TOP 10 * FROM FooTable ORDER BY X DESC) temp  --alias
ORDER BY X

or with a common table expression (CTE)

WITH Temp AS (SELECT TOP 10 * FROM FooTable ORDER BY X DESC) 

SELECT * FROM temp 
ORDER BY X



回答3:


ORDER BY clause is used to order the RESULT SET by a specified column.

Your query Select TOP 10 * from FooTable ORDER BY X DESC assuming X is the timestamp ,is not going to return the most recently inserted 10 rows. It will return the top 10 rows as stored (in whichever order) in the Database, and will then return the result set of the 10 such rows , in descending order. Hence your subquery should be modified to

Select TOP 10 * from (Select * from FooTable ORDER BY DESC) as T

This should fulfill your first requirement. You may then use this result set as an alias, to decide your final sort order.

I hope i have understood you correctly, when you say "I'm trying to get the top N records (when ordered by some column X)"




回答4:


An alternate solution to this question for all non-supported versions for TOP keyword is to use LIMIT. Example :-

SELECT * FROM 
   (SELECT * FROM FooTable ORDER BY X DESC LIMIT 10) as myAlias 
ORDER BY X ASC 


来源:https://stackoverflow.com/questions/2572496/select-top-n-records-ordered-by-x-but-have-results-in-reverse-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!