gpt4 book ai didi

sql - 按新选择的列排序

转载 作者:行者123 更新时间:2023-12-04 05:46:11 25 4
gpt4 key购买 nike

我有一个查询,如:

SELECT 
R.*
FROM
(SELECT A, B,
(SELECT smth from another table) as C,
ROW_NUMBER() OVER (ORDER BY C DESC) AS RowNumber
FROM SomeTable) R
WHERE
RowNumber BETWEEN 10 AND 20

这给了我一个错误 ORDER BY C DESC .

我明白为什么会导致这个错误,所以我想再添加一个 SELECTORDER BY并且只选择从 10 到 20 的行。但我认为有 3 个嵌套 SELECT 不好。命令。

还有什么可能选择这些行?

最佳答案

列不能引用同一级别的别名,您必须先对其进行表派生,或者使用 CTE。

SELECT 
R.* , ROW_NUMBER() OVER (ORDER BY C DESC) AS RowNumber
FROM
(SELECT A, B, (SELECT smth from another table) as C
FROM SomeTable) R
-- WHERE
-- but you still cannot do this
-- RowNumber BETWEEN 10 AND 20

需要这样做:
select S.*
from
(
SELECT
R.* , ROW_NUMBER() OVER (ORDER BY C DESC) AS RowNumber
FROM
(SELECT A, B,
(SELECT smth from another table) as C
FROM SomeTable) R
) as s
where s.RowNumber between 10 and 20

为了避免深度嵌套并使其至少看起来令人愉快,请使用 CTE:
with R as
(
SELECT A, B, (SELECT smth from another table) as C
FROM SomeTable
)
,S AS
(
SELECT R.*, ROW_NUMBER() OVER (ORDER BY C DESC) AS RowNumber
FROM R
)
SELECT S.*
FROM S
WHERE S.RowNumber BETWEEN 1 AND 20

关于sql - 按新选择的列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10652208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com