我有4张表发票,发票项目,收据和发票收据表格如下。
invoice_receipt用作invn_invoice和payment_receipt_master表之间的联结表。我想通过总结invoice_receipt_master.amount_paid了解每张发票的支付金额。
通过以下查询,我可以获得发票总额:
select invn.id AS invoice_id, invn.invoice_date AS invoice_date,
sum(invnitms.sub_total) AS total
from invn_invoice invn
right join invn_invoice_items invnitms on(invnitms.invoice_id = invn.id)
group by invn.id
但我的问题是我无法总结为每张发票支付的收据。我需要在总额旁边添加另一列作为支付金额,每张发票的收据总额。 任何帮助将不胜感激。
答案 0 :(得分:0)
你走了:
SELECT invn.id, SUM(receipt.amount_paid)
FROM invn_invoice invn JOIN invoice_receipt ir ON invn.id = ir.invoice_master_id
JOIN payment_receipt_master receipt ON ir.receipt_master_id = receipt.id
GROUP BY invn.id;
答案 1 :(得分:0)
由于发票项目和付款收据与发票的关系均为1:n,因此您无法在单个查询中对两个表进行求和。记录会重复,因此计算的总和会更高。您必须执行子查询中的一个求和以通过发票获得单个记录:
select invn.id AS invoice_id, invn.invoice_date AS invoice_date,
sum(invnitms.sub_total) AS total, coalesce(t.sum_paid, 0)
from invn_invoice invn
left join invn_invoice_items invnitms on(invnitms.invoice_id = invn.id)
left join (select invoice_master_id, sum(amount_paid) as sum_paid
from invoice_receipt ir
inner join payment_receipt_master prm on ir.receipt_master_id=prm.id
group by ir.invoice_master_id) t on t.invoice_master_id=invn.id
group by invn.id, invn.invoice_date, t.sum_paid
答案 2 :(得分:-1)
希望这能解答你的问题
with ctereceipt
as
(
select ir.invoice_master_id,SUM(prm.amount_paid) amount_paid from invoice_receipt ir
inner join payment_receipt_master prm on prm.id=ir.receipt_master_id
group by ir.invoice_master_id
)
select invn.id AS invoice_id, invn.invoice_date AS invoice_date,
sum(invnitms.sub_total) AS total,sum(ctr.amount_paid) as amountpaid
from invn_invoice
invn inner join invn_invoice_items invnitms on invnitms.invoice_id = invn.id
inner join ctereceipt ctr on ctr.invoice_master_id=invn.id
group by invn.id,invn.invoice_date