2

我有一个像这样的查询:

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命令并不好。

还有什么办法可以选择这些行?

4

2 回答 2

2

列不能引用同一级别的别名,您必须先对其进行表派生,或者使用 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
于 2012-05-18T12:10:13.007 回答
1

您不能在同一个中使用别名列SELECT,但您可以将其包装到另一个选择中以使其工作:

SELECT R.*
FROM (SELECT ABC.A, ABC.B, ABC.C, ROW_NUMBER() OVER (ORDER BY C DESC) AS RowNumber
      FROM (SELECT A, B, (SELECT smth from another table) as C FROM SomeTable) ABC 
) R
WHERE R.RowNumber BETWEEN 10 AND 20
于 2012-05-18T12:00:00.997 回答