MySQL: Group by two columns and sum

Based on your example table, it appears you want to be grouping on product rather than id. You merely need to add the Size column to both the SELECT list and the 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)']

Leave a Comment