简体   繁体   English

MySQL:按两列分组并求和

[英]MySQL: Group by two columns and sum

Building an inventory system.建立库存系统。 I have lots of products and each product has three different variables.我有很多产品,每个产品都有三个不同的变量。 So for stock totals I want to group by the two columns (product & size) and sum quantity to get stock total.因此,对于库存总量,我想按两列(产品和尺寸)和总数量进行分组以获得库存总量。

product产品 Size尺寸 Quantity数量
Widget one小工具一 2 2 275 275
Widget one小工具一 2 2 100 100
Widget two小工具二 3 3 150 150
Widget two小工具二 2 2 150 150

What I want for output:我想要的输出:

product产品 Size尺寸 Quantity数量
Widget one小工具一 2 2 375 375
Widget two小工具二 3 3 150 150
Widget two小工具二 2 2 150 150

I figured out how to group by one column and sum using the code below:我想出了如何按一列分组并使用以下代码求和:

$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 />";
}
?>

I am just stuck on grouping by both columns.我只是坚持按两列分组。 Is it possible?是否可以? or should I just create three different products for the of the three sizes and eliminate that column?或者我应该只为三种尺寸创建三种不同的产品并消除该列? Thanks.谢谢。

Based on your example table, it appears you want to be grouping on product rather than id .根据您的示例表,您似乎希望对product而不是id进行分组。 You merely need to add the Size column to both the SELECT list and the GROUP BY您只需要将Size列添加到SELECT列表和GROUP BY

$query = "SELECT 
            product,
            Size, 
            SUM(Quantity) AS TotalQuantity 
          FROM inventory
          GROUP BY product, Size";

Note that I have added a column alias TotalQuantity , which will allow you to more easily retrieve the column from the fetched row via the more sensible $row['TotalQuantity'] , rather than $row['SUM(Quantity)']请注意,我添加了一个列别名TotalQuantity ,这将允许您通过更合理的$row['TotalQuantity']而不是$row['SUM(Quantity)']更轻松地从获取的行中检索列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM