2016-07-14 107 views
1

我有orders表,order_detailsMySQL的總和列

我加入ordersorder_details表,使看起來像這樣的

order_id | customer_id | Quantity | 
     2 |   2 | 10 | 
     2 |   2 | 25 | 
     2 |   2 | 5  | 
     2 |   2 | 15 | 
     3 |   2 | 25 | 

我所試圖實現的是一個臨時表總和Quantity列,其中order_id相同。

所以最終的結果是這樣的

order_id | customer_id | Quantity | 
     2 |   2 | 55 | 
     3 |   2 | 25 | 

我的SQL語句才能到這裏看起來像這樣

SELECT 
     orders.orders_id, 
     orders.customer_id_fk, 
     sum(order_detail.quantity) 
     FROM orders 
     LEFT JOIN order_detail on orders.orders_id = order_detail.orders_id_fk 
     WHERE customer_id_fk IN(2) <-- this is needed because I only want to see customer 2. 

我怎麼把一個條件上的總和?

+1

親愛使用GROUP BY ORDER_ID – dev

+0

是的,我沒有,因爲我通過後,其中有一個順序,我把組按訂單後.... – codenoob

回答

1

看起來你很近!

您應該能夠通過組由order_id

SELECT 
     orders.orders_id, 
     orders.customer_id_fk, 
     sum(order_detail.quantity) 
     FROM orders 
     LEFT JOIN order_detail on orders.orders_id = order_detail.orders_id_fk 
     WHERE customer_id_fk IN(2) GROUP BY orders.orders_id,orders.customer_id_fk 
1

使用組。對不起,我被騙了。我在Order by之後放置了GROUP BY,但它沒有工作。下面sovled它

SELECT 
     orders.orders_id, 
     orders.customer_id_fk, 
     sum(order_detail.quantity) 
     FROM orders 
     LEFT JOIN order_detail on orders.orders_id = order_detail.orders_id_fk 
     WHERE customer_id_fk IN(2) 
     GROUP BY orders_id 
     ORDER BY customer_id 
0

這裏是OP獲得的唯一order_id的List與Quantity總和每個order_id

SELECT 
orders.orders_id, 
orders.customer_id_fk, 
sum(order_detail.quantity) 
FROM orders 
LEFT JOIN order_detail on orders.orders_id = order_detail.orders_id_fk 
WHERE customer_id_fk IN(2) 
GROUP BY orders.orders_id,orders.customer_id_fk