I am trying to query top 3 customers. I have 3 tables:
- Customer table (CustomerID, Company)
- Product table (ProductID, ProductName, Price)
- Order table (OrderID, Date, Amount, CustomerID)
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
If you see this table:
- 10042 has ordered $180 worth of products
- 10043 has ordered $110 worth of products
- 10044 has order $100 worth of products
How do I query this information like this:
Top 3 Customers
CustomerID Company Cost of Products Ordered 10042 HP $180 10043 Acer $110 10044 Sony $100
Currently I have this mysql but its not displaying as how I want it. Can someone help to point out my mistake?
$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";
Currently, i’m getting this:
Top 3 Customers
CustomerID Company Cost of Product Ordered
10042 HP 80.00
10043 Acer 20.00
10044 Sony 40.00
I’m using this code to display:
$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>";
Use
SUMinstead ofCOUNT: