MYSQL SUM行和GROUP by

时间:2015-02-09 10:26:09

标签: php mysql

大家好,并提前谢谢, 我有一个包含多种产品,价格和数量的表格,我想按产品添加数量和分组。

实施例

Description   Price  Quantity
Dojo hat      9.99   4
Dojo jeans    49.99  3
Dojo hat      9.99   4
Dojo jeans    49.99  1
Dojo t-shirt  19.99  2
Dojo hat      9.99   6
Dojo jeans    49.99  7

我希望它看起来像这样。

Description   Price  Quantity
Dojo hat      9.99   15
Dojo jeans    49.99  14
Dojo t-shirt  19.99  9

这是我当前的代码

SELECT products.description, products.price, SUM(orders.quantity) AS 'quantity'
FROM orders 
LEFT JOIN products
ON products.id = products.id
GROUP BY products.id;

Description   Price  Quantity
Dojo hat      9.99   80
Dojo jeans    49.99  80
Dojo t-shirt  19.99  80

再次感谢!

答案:)

SELECT products.description, products.price, sum(orders.quantity) AS 'quantity'
FROM orders
LEFT JOIN products
ON products.id = orders.products_id
GROUP BY products.id;

2 个答案:

答案 0 :(得分:2)

SELECT products.description, 
       products.price, 
       SUM(orders.quantity) AS sum_quantity
FROM orders 
LEFT JOIN products ON products.id = products.id
GROUP BY products.description, products.price

答案 1 :(得分:0)

  

按说明和价格分组

SELECT products.description, 
       products.price, 
       SUM(orders.quantity) AS 'quantity'
FROM orders 
LEFT JOIN products
ON products.id = products.id
GROUP BY products.description,products.price;