我有 3 张桌子
发票:身份证,客户
服务:invioce_id,价格
付款:invoice_id,金额
我想为每张发票选择所有服务价格为 amountDue 和任何付款金额为 amountPaid 的发票。
因此,例如,如果我有以下行:
发票
id = 1, client = 232
id = 2, client = 535
服务
invoice_id = 1, price = 5.00
invoice_id = 1, price = 10.00
invoice_id = 2, price = 20.00
付款
invoice_id = 1, amount = 7.00
invoice_id = 2, amount = 12.00
invoice_id = 2, amount = 8.00
我希望所有发票行的结果查询类似于:
发票
id = 1, client = 232, amountDue = 15.00, amountPaid = 7.00
id = 2, client = 535, amountDue = 20.00, amountPaid = 20.00
我有一个这样的查询:
SELECT invoices.*,
sum(services.price) AS amountDue,
sum(payments.amount) AS amountPaid
FROM invoices
LEFT JOIN services ON services.invoice = invoices.id
LEFT JOIN payments ON invoices.id = payments.invoice
GROUP BY invoices.id
但是得到的金额被乘以每张发票的服务数量。
有没有办法通过一个查询来提取所有数据?