MySQL大小写、总和、分组依据

2022-08-04 00:00:00 sum group-by mysql case
我希望根据PaymentStatus值从两个不同的列获得支付状态的总和-但此查询返回NULL作为总和。为什么它不工作?

select payment_status,
CASE 
WHEN 'PAID' THEN sum(paid_amount)
when 'Not Paid' then sum(total_amount_due )
END 
from monthly_fee
group by payment_status;

解决方案

您可以尝试以下查询:

select sum(if(payment_status = 'PAID', paid_amount, 0) 
       + if(payment_status = 'Not Paid', total_amount_due, 0)) 
from monthly_fee
group by payment_status;

相关文章