我有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.
如何在总和上加上条件?
答案 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