MySQL:找出客户花费最多的商店

时间:2009-10-07 19:03:58

标签: sql mysql

根据提取客户姓名和电话号码的特定搜索条件生成自动呼叫列表。

共有4个表:Customer,Phone_Numbers,Sales_Header,Sales_Detail。

查询如下:

SELECT CONCAT(customer.First_Name, ‘’, customer.Last_Name), 
       Phone_Numbers.Number, 
       Customer.ID 
FROM Sales_Header 
INNER JOIN Sales_Detail ON Sales_Detail.Header_ID = Sales_Header.ID 
INNER JOIN Customer ON Customer.ID = Sales_Header.Customer_ID 
INNER JOIN Phone_Numbers ON Phone_Numbers.Customer_ID = Customer.ID 
WHERE Sales_Header.WebSale = -1 
  AND Sales_Detail.Price > 1000 
  AND DateSold > 20081002

问题:

sales_header中的每个销售都有一个商店位置(销售它的商店的ID)。 但是,顾客可以从多个商店购买。我需要找出客户花费最多的商店,并将该商店添加到上面的select语句输出中。

2 个答案:

答案 0 :(得分:1)

如果您使用的是MySQL,我相信它是:

SELECT CONCAT(customer.First_Name, ‘’, customer.Last_Name), 
       Phone_Numbers.Number, 
       Customer.ID, Sales_Detail.ID, Sum(Sales_Detail.Price) 
FROM Sales_Header 
INNER JOIN Sales_Detail ON Sales_Detail.Header_ID = Sales_Header.ID 
INNER JOIN Customer ON Customer.ID = Sales_Header.Customer_ID 
INNER JOIN Phone_Numbers ON Phone_Numbers.Customer_ID = Customer.ID 
WHERE Sales_Header.WebSale = -1 
  AND Sales_Detail.Price > 1000 
  AND DateSold > 20081002
GROUP BY CONCAT(customer.First_Name, ‘’, customer.Last_Name), 
       Phone_Numbers.Number, 
       Customer.ID, Sales_Detail.ID
ORDER BY Sum(Sales_Detail.Price) Desc Limit 1;

在SQL Server中,你在Concat之前做“前1”。

此外,根据您的表格的布局,您还需要在“concat”之前添加“distinct”(没有括号或逗号),以删除重复项。

答案 1 :(得分:0)

尝试使用SUM,GROUP BY和ORDER BY ...这样做可以吗?

SELECT CONCAT(customer.First_Name, ‘’, customer.Last_Name), 
       Phone_Numbers.Number, 
       Customer.ID,
       SUM(Sales_Detail.Price) AS Total_Purchases
FROM Sales_Header 
INNER JOIN Sales_Detail ON Sales_Detail.Header_ID = Sales_Header.ID 
INNER JOIN Customer ON Customer.ID = Sales_Header.Customer_ID 
INNER JOIN Phone_Numbers ON Phone_Numbers.Customer_ID = Customer.ID 
WHERE Sales_Header.WebSale = -1 
  AND Sales_Detail.Price > 1000 
  AND DateSold > 20081002
GROUP BY Customer.ID
ORDER BY Total_Purchases