gpt4 book ai didi

SQL优化Case语句

转载 作者:行者123 更新时间:2023-12-04 15:02:15 26 4
gpt4 key购买 nike

我相信我可以通过使用左外连接的 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;

最佳答案

您可以将其简化为使用单个查询而不是两个查询。您仍然需要那个,因为 UPDATE 中的 GROUP BY 不起作用。

UPDATE bi 
SET payments = bd.payments,
charges= bd.charges,
balance = bd.balance
FROM billing bi
LEFT JOIN (SELECT bd.inv,
payments = Round(Sum(CASE
WHEN code_type IN ( 'AB' , 'CD' ) THEN
bd.bal
ELSE 0
END), 2),
charges = Round(Sum(CASE
WHEN code_type NOT IN ( 'AB' , 'CD' ) THEN
bd.bal
ELSE 0
END), 2),
balance = Round(Sum(bd.bal), 2)
FROM bill bd
GROUP BY bd.inv) bd
ON bd.inv = bi.inv

关于SQL优化Case语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10385597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com