Mysql查询前3名客户

时间:2012-08-31 03:53:52

标签: php mysql

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

  • 客户表(CustomerID,公司)
  • 产品表(ProductID,ProductName,Price)
  • 订单表(订单ID,日期,金额,客户ID)
OrderID     Date        Amount      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  Company     Cost of Products Ordered
10042       HP      $180
10043       Acer        $110
10044       Sony        $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>";

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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