0

我想选择每个客户购买的最昂贵的产品,但我在 3 个表中提供了信息:客户、购买、产品价格。

表格如下所示:

顾客:

Customer_ID | Customer_Name

购买:

Customer_ID | Product_ID

产品价格:

Product_ID | Price

我正在运行的是:

SELECT  
Customer_Name, max(Price), Purchases.Product_ID
            FROM Customers 
            LEFT JOIN Purchases 
            ON Customers.Customer_ID=Purchases.Customer_ID
            LEFT JOIN ProductPrices
            ON Purchases.Product_ID=ProductPrices.Product_ID
                        GROUP BY Customer_Name
                        ORDER BY ABS(Price) DESC
                        ;

我得到的输出是名称和最高购买正确,但 product_id 是第一个,并且与最高价格无关。

你能帮我找出我做错了什么吗?

编辑:

为了让你更容易,我创建了这个:

http://sqlfiddle.com/#!2/db7f9/1

4

2 回答 2

2

尝试这个:

select distinct c.Customer_Name,pp.Product_Id,m.Price
from 
  (select Customer_ID,max(Price) as Price
  from Purchases p join ProductPrices pp on (p.Product_ID=pp.Product_ID)
  group by Customer_ID) m
join Customers c on (m.Customer_ID=c.Customer_ID)
join ProductPrices pp on (pp.Price=m.Price)
join Purchases p on (m.Customer_ID=p.Customer_ID and p.Product_ID=pp.Product_ID)

注意:如果客户以相同的价格购买了多个产品,这将为每个客户提供多行。

于 2013-10-12T11:19:06.590 回答
-1

尝试这个

    SELECT Customer_Name, max(Price) price , Product_ID FROM (
 SELECT  
Customer_Name, Price, Purchases.Product_ID
        FROM Customers 
        INNER JOIN Purchases 
        ON Customers.Customer_ID=Purchases.Customer_ID
        INNER JOIN ProductPrices
        ON Purchases.Product_ID=ProductPrices.Product_ID


                    ORDER BY ABS(Price) DESC
)t

GROUP BY Customer_Name

在这里演示

输出:

  CUSTOMER_NAME     PRICE   PRODUCT_ID
     John           30000   3
     Kate           30000   3
     Peter          20000   2
于 2013-10-12T11:46:37.963 回答