select
`sites`.`number`,
SUM(invoices.amount),
SUM(payment_details.amount) as pda,
COUNT(warrels.id) as warrels
from `sites`
left join `invoices`
on `sites`.`id` = `invoices`.`invoiceable_id`
left join `warrels`
on `sites`.`id` = `warrels`.`site_id`
left join `payment_details`
on `invoices`.`id` = `payment_details`.`payable_id`
where `invoices`.`invoiceable_type` = 'App\\Models\\Site'
and `sites`.`number` LIKE 'AU22%'
group by `sites`.`number`
order by `sites`.`number` asc
在大多数情况下,这会返回正确计算的总和。我以简化的方式计算总体余额。
但是当有多个
payment_details
与发票关联时,invoices.amount
的 SUM 会在总和中添加一个重复项。如果我删除 payment_details
上的连接,invoices.amount
的总和总是正确返回。
但是有一些,当有多个 payment_details 与发票相关联时,发票的 SUM.amount 会在总和中添加一个副本。
您通常会在加入之前通过子查询中的发票预先聚合付款详细信息:
select s.number,
SUM(i.amount),
SUM(pd.amount) as pda,
COUNT(w.id) as warrels
from sites s
left join invoices i on s.id = i.invoiceable_id and i.invoiceable_type = 'App\\Models\\Site'
left join warrels w on s.id = w.site_id
left join (
select payable_id, sum(pd.amount)
from payment_details
group by payable_id
) pd on i.id = pd.payable_id
where s.number LIKE 'AU22%'
group by s.number
order by s.number
请注意,由于您似乎打算使用
left join
s,因此我将 invoices
上的条件从 where
子句移动到连接的 on
子句。