2012-01-12 61 views
0

我目前正在使用隨SQL Server一起提供的Northwind示例數據庫。我正在嘗試編寫一個查詢,以查找「與Northwind訂單花費超過25,000美元的客戶」。在同樣情況下我寫了下面的查詢:Northwind示例數據庫的SQL查詢問題

select a.customerid, sum (b.unitprice*b.quantity) as Total_Amount 
from orders a join [order details] b on a.orderid=b.orderid 
--where Total_Amount > 25000 --ERROR: In this filter condition, SQL Server is not recongnizing "Total_Amount" 
group by a.customerid 
order by Total_Amount desc 

查詢似乎除了一個事實,我無法把過濾條件(25000,請參見注釋行的正常工作查詢),因爲它似乎SQL Server不能識別過濾條件中的別名(即Total_Amount)。但它正在識別Order By子句中的別名。

請幫我用正確的方法來處理這個查詢,以及可能的解決方法是什麼?

感謝, XM在WHERE子句中

回答

0
Select * FROM (
select a.customerid, sum (b.unitprice*b.quantity) as Total_Amount 
from orders a join [order details] b on a.orderid=b.orderid 
--where Total_Amount > 25000 --ERROR: In this filter condition, SQL Server is not recongnizing "Total_Amount" 
group by a.customerid 
) as a 
WHERE a.Total_Amount > 25000 
order by Total_Amount desc 
1

不能使用別名。

由於SUM是一個聚合函數,您需要將其移至HAVING子句。

這與查詢執行的順序(邏輯查詢處理階段)有關於此here的詳細文章。

SELECT a.customerid, sum (b.unitprice*b.quantity) as Total_Amount 
FROM orders a join [order details] b on a.orderid=b.orderid 
GROUP BY a.customerid 
HAVING SUM(b.unitprice*b.quantity) > 25000 
ORDER BY Total_Amount desc 
3

嘗試

select a.customerid, sum (b.unitprice*b.quantity) as Total_Amount 
from orders a join [order details] b on a.orderid=b.orderid 
group by a.customerid 
having sum (b.unitprice*b.quantity) > 25000 
order by sum(b.unitprice*b.quantity) desc 

另外,儘量看看the Having clause documentation