无法按外部顺序引用子查询列

时间:2012-08-24 14:26:28

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

下面的ORDER BY子句导致错误。如何在ORDER BY子句中引用TotalPrice列:

SELECT * FROM
(

SELECT O.OrderID,
       (SELECT SUM(SubTotal) FROM DB_OrderDetails OD WHERE OD.OrderID = O.OrderID) AS TotalPrice,
       ROW_NUMBER() OVER (ORDER BY TotalPrice) AS RowNum

    FROM DB_Orders O

) Orders

2 个答案:

答案 0 :(得分:4)

您无法在同一个子查询中通过其名称引用它,您可以在外部查询中执行此操作:

SELECT orders.*, 
       ROW_NUMBER() OVER (ORDER BY TotalPrice) AS RowNum FROM
(
    SELECT O.OrderID,
       (SELECT SUM(SubTotal) FROM DB_OrderDetails OD 
        WHERE OD.OrderID = O.OrderID) AS TotalPrice
    FROM DB_Orders O
) Orders

答案 1 :(得分:1)

这个怎么样:

select 
    o.orderID,
    sum(od.SubTotal) as TotalPrice,
    row_number() over (order by sum(od.SubTotal)) as RowNum
from DB_Orders o
join DB_OrderDetails od
    on o.OrderID = od.OrderID
group by o.OrderID

以下是示例:SQL Fiddle