mysql - Combine Sum with select join and union -
i need join 2 query this
select * contracts join customers on customer.id=contracts.customer
and (12234 explample customer)
select *,sum(cast(amount unsigned)) total from( select * invoices customer='123456' union select * paypal_invoices customer='123456') t1
in first query extract normal customers list based on actives contracts have.
in second extract sum of invoice specific customers
so need extract customers first query need column sum of invoice specific customer. thank you.
one method correlated subqueries or left join
s:
select co.*, cu.*, i.amount, pi.amount paypal_amount, ( coalesce(i.amount, 0) + coalesce(pi.amount, 0) ) total contracts co join customers cu on cu.id = co.customer left join (select customer, sum(amount) amount invoices group customer ) on i.customer = cu.id left join (select customer, sum(amount) amount paypal_invoices group customer ) pi on pi.customer = cu.id;
two key ideas here. first, sure aggregate before doing joins. prevents joins multiplying number of rows , generating incorrect results. similarly, uses left join
ensure customers included, no invoices.
second idea: don't use union
. query, in fact, possibly incorrect. union
removes duplicates -- both within table , between tables. safer use union all
. or, in case, not needed @ all.
Comments
Post a Comment