简体   繁体   中英

SUM Multiple Columns by Group BY

I have these datas on my database

Purchase ID: 0012 <br>
Product: 1 <br>
Delivered: 100

Pruchase ID: 0013<br>
Product: 1<br>
Delivered: 10

When i sum the same products, it should be 110 but when I use this query, the sum will be 440

SELECT `purchase_orders`.`product`, SUM(purchase_orders.delivered) as system_count, `products`.`code`
FROM `purchase_orders`
JOIN `products` ON `products`.`id` = `purchase_orders`.`product`
WHERE `purchase_orders`.`delivery_status` = 4
GROUP BY `purchase_orders`.`product`

Can anyone help me what is wrong with my SQl?

You should GROUP BY products.code as well.

Like below

SELECT `purchase_orders`.`product`, SUM(purchase_orders.delivered) as system_count, `products`.`code`
FROM `purchase_orders`
JOIN `products` ON `products`.`id` = `purchase_orders`.`product`
WHERE `purchase_orders`.`delivery_status` = 4
GROUP BY `purchase_orders`.`product`, `products`.`code`
select po.Product, sum(po.Delivered) as count from purchase_orders po
group by po.Product

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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