23

我想在使用 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

但这没有用。我该如何解决?

4

6 回答 6

27

只要您为子查询设置别名,这应该可以工作。

SELECT q.* 
    FROM (SELECT TOP 3 * 
              FROM table 
              ORDER BY id DESC) q
    ORDER BY q.id ASC
于 2012-09-21T16:18:56.480 回答
6

我想你忘记了子选择别名

SELECT * 
FROM (
    SELECT TOP 3 * 
    FROM table 
    ORDER BY id DESC
) s
ORDER BY id ASC
于 2012-09-21T16:20:40.663 回答
2

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

于 2012-09-21T16:19:05.580 回答
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
于 2012-09-21T16:19:25.340 回答
1
SELECT * FROM (SELECT TOP 3 * FROM table ORDER BY id DESC) AS r ORDER BY r.id ASC

我想到了。我需要制作一个临时表并使用 AS 命名。

于 2012-09-21T16:19:10.830 回答
0
SELECT *
FROM (
    SELECT *
    FROM table
    ORDER BY ID DESC
) TMP
ORDER BY TMP.ID ASC
于 2013-07-08T04:24:17.713 回答