简体   繁体   中英

sql server reverse order after using desc

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, any suggestions?

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

I think you forgot the subselect alias

SELECT * 
FROM (
    SELECT TOP 3 * 
    FROM table 
    ORDER BY id DESC
) s
ORDER BY id ASC

SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) As AliasName ORDER BY id ASC

;WITH cte
AS
(
   SELECT *, ROW_NUMBER() OVER(ORDER BY id DESC) rank
   FROM table
)
SELECT * 
FROM cte
WHERE rank <= 3 
ORDER BY id ASC
SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) AS r ORDER BY r.id ASC

想通过使用AS来使临时表具有名称

SELECT *
FROM (
    SELECT *
    FROM table
    ORDER BY ID DESC
) TMP
ORDER BY TMP.ID ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM