Reputation: 2711
I want to reverse the order in SQL Server of results after using desc. For example:
SELECT TOP 3 * FROM table ORDER BY id DESC
returns results:
505
504
503
But then I want to flip the results to look like this:
503
504
505
I tried
SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) ORDER BY id ASC
But that did not work. How can I fix it?
Upvotes: 23
Views: 41635
Reputation: 2711
SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) AS r ORDER BY r.id ASC
I figured it out. I needed to make a temporary table and have a name using AS.
Upvotes: 1
Reputation: 3802
SELECT *
FROM (
SELECT *
FROM table
ORDER BY ID DESC
) TMP
ORDER BY TMP.ID ASC
Upvotes: 0
Reputation: 79929
;WITH cte
AS
(
SELECT *, ROW_NUMBER() OVER(ORDER BY id DESC) rank
FROM table
)
SELECT *
FROM cte
WHERE rank <= 3
ORDER BY id ASC
Upvotes: 2
Reputation: 125254
I think you forgot the subselect alias
SELECT *
FROM (
SELECT TOP 3 *
FROM table
ORDER BY id DESC
) s
ORDER BY id ASC
Upvotes: 7
Reputation: 24498
SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) As AliasName ORDER BY id ASC
Upvotes: 2
Reputation: 135808
That should work as long as you alias the subquery.
SELECT q.*
FROM (SELECT TOP 3 *
FROM table
ORDER BY id DESC) q
ORDER BY q.id ASC
Upvotes: 28