建立库存系统。我有很多产品,每个产品都有三个不同的变量。因此,对于总库存,我想按两列(产品和尺寸)和总数量分组以获得总库存。
--------------------------------- |product |Size |Quantity | --------------------------------- |Widget one |2 |275 | --------------------------------- |Widget one |2 |100 | --------------------------------- |Widget two |3 |150 | --------------------------------- |Widget two |2 |150 | ---------------------------------
我想要输出的内容: 小部件一-2:375 小部件二-3:150 小部件二-2:150
我想出了如何使用以下代码将一列分组并求和:
$query = "SELECT product, SUM(Quantity) FROM inventory GROUP BY product"; $result = mysql_query($query) or die(mysql_error()); // Print out result while($row = mysql_fetch_array($result)){ echo "Total ". $row['product']. " = ". $row['SUM(Quantity)']; echo "<br />"; } ?>
我只是按两列分组。可能吗?还是应该仅针对这三种尺寸的商品创建三种不同的产品并删除该列?谢谢。
根据示例表,您似乎希望分组product而不是id。您只需要将Size列添加到SELECT列表和GROUP BY
product
id
Size
SELECT
GROUP BY
$query = "SELECT product, Size, SUM(Quantity) AS TotalQuantity FROM inventory GROUP BY product, Size";
请注意,我添加了一个列别名TotalQuantity,这将让您更轻松地通过更明智的检索所取得的行的列$row['TotalQuantity'],而不是$row['SUM(Quantity)']
TotalQuantity
$row['TotalQuantity']
$row['SUM(Quantity)']