我有一个包含 4 个表的小型数据库:客户 - 订单 - 订单线 - 产品,我正在玩一些查询,并试图获取订单最昂贵的人的姓名。
在玩了一些之后,我想出了以下查询,它显示了所有订单的价格:
SELECT SUM(OrderLine.Amount * Product.Price) AS OrderLinePrice, Orders.Id, Customer.Lastname
FROM OrderLine, Product, Orders, Customer
WHERE OrderLine.ProductId = Product.Id
AND Orders.Id = OrderLine.OrderId
AND Customer.Id = Orders.CustomerId
GROUP BY Orders.Id, Customer.Lastname
ORDER BY OrderLinePrice DESC
现在我在概念上需要做或认为我需要做的是应用 MAX() 来仅选择最高的 OrderLinePrice,但我没有成功使用 SQL Server 抱怨无法在表达式上执行聚合函数包含一个聚合...
=============== 更新:
目前我的查询如下所示:
SELECT t.CustomerLastName
FROM (
SELECT SUM(OrderLine.Amount * Product.Price) AS OrderLinePrice, Orders.Id, Customer.Lastname AS CustomerLastName
FROM OrderLine, Product, Orders, Customer
WHERE OrderLine.ProductId = Product.Id
AND Orders.Id = OrderLine.OrderId
AND Customer.Id = Orders.CustomerId
GROUP BY Orders.Id, Customer.Lastname
) AS t
WHERE t.OrderLinePrice =
(
SELECT MAX(s.OrderLinePrice) AS MaxOrderPrice
FROM (
SELECT SUM(OrderLine.Amount * Product.Price) AS OrderLinePrice, Orders.Id, Customer.Lastname AS CustomerLastName
FROM OrderLine, Product, Orders, Customer
WHERE OrderLine.ProductId = Product.Id
AND Orders.Id = OrderLine.OrderId
AND Customer.Id = Orders.CustomerId
GROUP BY Orders.Id, Customer.Lastname
) AS s
)
ORDER BY CustomerLastName
这将检索客户列表,其中他们的订单价格等于最昂贵订单的价格。这正好检索到我想要的东西,但感觉非常多余。
我应该如何开始提高效率(如果可能)?