3

我正在尝试查询前 3 名客户。我有 3 张桌子:

  • 客户表(CustomerID、Company)
  • 产品表(ProductID、ProductName、Price)
  • 订单表(OrderID、Date、Amount、CustomerID)
OrderID 日期 金额 CustomerID
19 2012-08-24 20 10043
20 2012-08-24 40 10044
21 2012-08-24 60 10044
22 2012-08-24 80 10042
23 2012-08-24 90 10043
24 2012-08-24 100 10042
25 2012-08-24 50 10041

如果您看到此表:

  • 10042 订购了价值 180 美元的产品
  • 10043 订购了价值 110 美元的产品
  • 10044 订购了价值 100 美元的产品

如何像这样查询这些信息:

前 3 名客户

CustomerID 公司订购产品的成本
10042 马力 180 美元
10043 宏基 $110
10044 索尼 100 美元

目前我有这个mysql,但它没有按我想要的方式显示。有人可以帮助指出我的错误吗?

$query = "SELECT 
    CustomerOrder.CustomerID, CustomerOrder.Amount, 
    Customer.Company, 
    count(CustomerOrder.Amount) as total_amount
FROM 
    `CustomerOrder` 
     INNER JOIN Customer ON Customer.CustomerID = CustomerOrder.CustomerID
GROUP BY CustomerID 
ORDER BY total_amount DESC LIMIT 3";

目前,我得到这个:

 Top 3 Customers

CustomerID  Company         Cost of Product Ordered
10042       HP          80.00
10043       Acer            20.00
10044       Sony            40.00

我正在使用此代码来显示:

$result = mysql_query($query);
$num=mysql_numrows($result);
echo "<table border='1'>
<tr>
<th>CustomerID</th>
<th>Company</th>
<th>Cost of Product Ordered</th>

</tr>";

while($row = mysql_fetch_array($result)) 
  {
  echo "<tr>";
  echo "<td>" . $row['CustomerID'] . "</td>";
  echo "<td>" . $row['Company'] . "</td>";
  echo "<td>" . $row['total_amount'] . "</td>";

  echo "</tr>";
  }
echo "</table>";
4

2 回答 2

1

使用SUM代替COUNT

SELECT 
    Customer.CustomerID,
    Customer.Company, 
    SUM(CustomerOrder.Amount) AS total_amount
FROM CustomerOrder
INNER JOIN Customer
ON Customer.CustomerID = CustomerOrder.CustomerID
GROUP BY Customer.CustomerID 
ORDER BY total_amount DESC
LIMIT 3
于 2012-08-31T03:58:47.950 回答
0

使用以下查询...我检查了它...它的工作

select ordr.CustomerID,cust.Company,(Sum(ordr.Amount)) as  'Cost of Products Ordered' from `order` ordr , customer cust where cust.CustomerID=ordr.CustomerID group by ordr.CustomerID order by Sum(ordr.Amount) desc limit 3
于 2012-08-31T04:48:10.877 回答