使用desc后sql server逆序

时间:2012-09-21 16:15:47

标签: sql sql-server

我想在使用desc后反转sql server中结果的顺序。例如:

SELECT TOP 3 * FROM table ORDER BY id DESC

返回结果:

505
504
503

但后来我想将结果翻转为:

503
504
505

我试过

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

但这没有用,有什么建议吗?

6 个答案:

答案 0 :(得分:23)

只要您对子查询进行别名,这应该可以正常工作。

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

答案 1 :(得分:5)

我想你忘记了subselect别名

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

答案 2 :(得分:2)

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

答案 3 :(得分:2)

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

答案 4 :(得分:1)

SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) AS r ORDER BY r.id ASC

认为需要使用AS

使临时表具有名称

答案 5 :(得分:0)

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