2012-08-31 64 views
3

我正在查詢前3名客戶。我有3個表:前3名客戶的Mysql查詢

  • 客戶表(客戶ID,公司)
  • 產品表(產品ID,產品名稱,價格)
  • 訂單表(訂單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有ordere d $ 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>"; 
+1

「目前我有這個MySQL,但它不顯示爲我想要它。」你能展示查詢給你什麼,並解釋它與你想要的不同嗎? –

+1

嗯。對我來說,「總數」和「數」似乎並不是一回事...... –

+0

@MarkByers我已經更新了我的問題。 – user1501784

回答

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 
+0

「但我收到錯誤」。什麼錯誤?另外,請不要在評論中張貼代碼。請更新您的問題,以包含回答您的問題所需的所有相關信息。 –

+0

我得到的錯誤是:警告:mysql_numrows()期望參數1是資源,布爾給出在C:\ xampp \ ....在線57 – user1501784

+0

好吧我添加了$結果= mysql_query($查詢)或死($ query。「

」.mysql_error());並得到這個錯誤:FUNCTION db.SUM不存在。檢查參考手冊 – user1501784

0

使用以下查詢...我c hecked它...它的工作

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