具有相同id的mysql sum列

时间:2016-07-14 18:05:07

标签: mysql sum

我有orders表,order_details

我将orders表加入order_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. 

如何在总和上加上条件?

3 个答案:

答案 0 :(得分:1)

看起来你非常接近!

您应该能够按order_id进行分组,以获取每个order_id

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

答案 1 :(得分:1)

使用分组

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

答案 2 :(得分:0)

这是OP。对不起我傻了。我在Order by之后放了GROUP BY,它没有用。以下所讨论的

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