Northwind示例数据库的SQL查询问题

时间:2012-01-12 08:30:46

标签: sql sql-server

我目前正在使用SQL Server附带的Northwind示例数据库。我正在尝试编写一个查询,以查找“使用Northwind在订单上花费超过25,000美元的客户”。在相同的上下文中,我编写了以下查询:

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

3 个答案:

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

答案 1 :(得分:1)

您不能在WHERE子句中使用别名。

由于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 

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