我相信我可以通过使用左外连接的 case 语句来优化这个 sql 语句。
但是我一直很难设置案例,一个用于总结代码类型 AB、CD,另一个用于所有其余的。
感谢您对此提供的任何帮助或提示。
update billing set payments = isnull(bd1.amount, payments)
, payments = case
when payments is null then 0
else payments
end
, charges = case
when bd2.amount is not null then charges
when charges is null then 0
else charges
end
, 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 = 'AB'
or code_type = '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 <> 'AB'
and code_type <> 'CD'
group by inv) bd2
on bd2.inv = bi.inv;