0

以下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
4

2 回答 2

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
于 2012-08-24T14:35:03.083 回答
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

于 2012-08-24T14:47:39.167 回答