如何在select中的另一列上使用Max函数

时间:2010-09-01 08:27:26

标签: sql sql-server-2008 aggregate-functions max

有询问被各位顾客买的喜欢的商品的询问。我必须选择并在第一个选择中我选择了每个客户购买的产品数量。在另一个选择中我想为每个客户选择最大的那个boughts。但是当我想选择max(前一个选择列)时,它得到并且错误并且说没有定义任何人可以帮助我如何解决这个问题。我很有动力从这个方面解决问题,我不愿意使用其他方法,如创建视图或类似的东西。任何人都可以帮助我:

SELECT INN.Maximum,INN.Name, customer.ProductName from
(SELECT ContactName, ProductName, COUNT([Order Details].Quantity) AS NumOftimeCustomer
FROM Orders, [Order Details], Products, Customers
WHERE [Order Details].OrderID = Orders.OrderID
AND [Order Details].ProductID = Products.ProductID
AND Orders.CustomerID = Customers.CustomerID
GROUP BY ContactName, ProductName)customer
INNER JOIN
(SELECT Customers.ContactName AS Name, **MAX(customer.numOftimecustomer)** AS Maximum 
from    Customers, customer 
GROUP BY Customers.ContactName) INN
ON INN.Name = customer.ContactName AND INN.Maximum = customer.NumOftimeCustomer

MAX(customer.numOftimecustomer) **中提到的部分是给出错误的部分,它表示没有定义对象客户。有没有办法解决它没有看法?为什么会这样?既然我定义的客户不是桌子?

1 个答案:

答案 0 :(得分:2)

这是你想要的:

select 
    *
 from  (SELECT ContactName, ProductName, COUNT([Order Details].Quantity) AS NumOftimeCustomer
    FROM Orders, [Order Details], Products, Customers
    WHERE [Order Details].OrderID = Orders.OrderID
    AND [Order Details].ProductID = Products.ProductID
    AND Orders.CustomerID = Customers.CustomerID
    GROUP BY ContactName, ProductName)customer
where customer.num = (select max(num) from

(SELECT ContactName, ProductName, COUNT([Order Details].Quantity) AS NumOftimeCustomer
    FROM Orders, [Order Details], Products, Customers
    WHERE [Order Details].OrderID = Orders.OrderID
    AND [Order Details].ProductID = Products.ProductID
    AND Orders.CustomerID = Customers.CustomerID
    GROUP BY ContactName, ProductName)customer2
 where customer2.name = customer.name)