我想在使用 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
但这没有用。我该如何解决?
我想在使用 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
但这没有用。我该如何解决?
只要您为子查询设置别名,这应该可以工作。
SELECT q.*
FROM (SELECT TOP 3 *
FROM table
ORDER BY id DESC) q
ORDER BY q.id ASC
我想你忘记了子选择别名
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