按新选择的列排序

时间:2012-05-18 11:55:33

标签: sql sql-server sql-order-by

我有一个类似的查询:

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命令。

如何选择这些行?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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