2013-10-14 42 views
0

我想使用以前订单中的信息制作“畅销品”清单。我现在拥有的是这样的东西;如何制作畅销品清单?

Product Quantity 
2227 30 
1722 3 
1851 7 
2227 10 
1722 4 
1863 1 
etc.... 

第一列(产品)是数据库中每个产品的唯一ID。数量当然有多少项目已经售出。每行是一个订单。因此ID 2227在此列表中出现两次。

我该如何对这些数据进行排序,以便共获得ID 2227的销售量?

我此刻的PHP是:

$SQL_best = "SELECT c.company, co.id, cod.productId, cod.quantity 
FROM customers c 
LEFT JOIN customers_orders co ON c.id = co.custId 
LEFT JOIN customers_orders_details cod ON co.id = cod.orderId 
WHERE c.reseller =1 
AND c.status != 99 
AND c.id = ".$intCustomerId; 

$result_best = $objDB->sqlExecute($SQL_best); 

*some html code here* 

<table style="margin:0px auto;"> 
<tr> 
    <th>Product</th> 
    <th>Quantity</th> 
</tr> 
<?php 
while($obj_best = $objDB->getObject($result_best)) { 
    if ($obj_best->quantity > 0) { // don't include negatve quantaties (RMA's/refunds) 
    echo "<tr>"; 
     echo "<td>".$obj_best->productId."</td>"; 
     echo "<td>".$obj_best->quantity."</td>"; 
    echo "</tr>"; 
    } 
} 
?> 
</table> 

MySQL查询

所以我需要加在一起的所有$obj_best->productId的。在这种情况下我该怎么做?或者我应该编辑我的查询?

+0

添加'SUM(cod.quantity)'到您的选择列表;然后按该列排序desc ....筛选出SQL查询中的负数,而不是PHP –

+1

您应该更改查询。您需要产品上带有GROUP BY子句的聚合函数SUM – AgRizzo

回答

0

这是一个想法,你改变了SQL字符串是这样的:

$SQL_best = "SELECT c.company, co.id, cod.productId, 
SUM(cod.quantity) AS quantity 
FROM customers c 
LEFT JOIN customers_orders co ON c.id = co.custId 
LEFT JOIN customers_orders_details cod ON co.id = cod.orderId 
WHERE c.reseller = 1 
AND c.status != 99 
AND c.id = " . $intCustomerId . " 
GROUP BY cod.productId 
HAVING quantity > 0 
ORDER BY quantity DESC";