Maybe something like this:
update billing set payments = isnull(bd1.amount, payments) , payments = isnull(payments, 0) , charges = isnull(bd2.amount, isnull(charges, 0)) , balance = round(charges + isnull(bd1.amount, bi.payments), 2) from billing bi left outer join (select inv, round(sum(bd1.bal), 2) amount from "bill" bd1 where code_type in ('AB', 'CD') group by inv) bd1 on bd1.inv = bi.inv left outer join (select invoice, round(sum(bd2.bal), 2) amount from "bill" bd2 where code_type not in ('AB', 'CD') group by inv) bd2 on bd2.inv = bi.inv;
Two left connections are not a problem!
source share