查询中的SUM,GROUP BY和LEFT JOIN

时间:2018-03-22 12:06:32

标签: mysql group-by sum left-join

我有两张桌子:

`orders`
order_id    order_office_id     order_invoice_id  
1           1                   1
2           2                   2
3           2                   2
4           2                   3
5           1                   4

`invoices`
inv_id    inv_order_id  inv_amount  
1         1             500.00       
2         0             320.00
3         3             740.00
4         4             160.00

使用此查询:

SELECT SUM(inv_amount) matrah, order_office_id
FROM `invoices` 
LEFT JOIN orders ON order_invoice_id = inv_id OR inv_order_id = order_id
WHERE order_id IS NOT NULL
GROUP BY order_office_id

它正在增加一些数量。

我希望通过办公室获得金额总和:

office_id         sum
1              660.00
2             1060.00

如何通过单一查询获得适当的金额?

2 个答案:

答案 0 :(得分:1)

这就是你想要的,我想

select sum(inv_amount) as matrah,
(select order_office_id from orders where order_invoice_id = inv_id  limit 1) as office
from invoices
group by office;

我删除了OR,因为你为其中一个订单获得了两个办公室id,所以它很模糊。我已经包含了一个子查询,以确保每个订单只应用一个办公室。

答案 1 :(得分:0)

此查询可能会帮助您:

SELECT SUM(i.inv_amount) matrah, o.order_office_id
FROM `invoices` AS i
LEFT JOIN `orders` AS o 
ON o.order_invoice_id = i.inv_id
GROUP BY order_office_id

ON状态下的OR语句导致了问题。