当存在空值时,从两个表中减去两个值

时间:2012-06-21 13:01:32

标签: mysql

select p.partnerid,
sum(case when c.amount is not null then c.amount else 0 end) as amount,
sum(case when c.netamt is not null then c.netamt else 0 end) as total,
sum(case when (c.netamt - d.paidamount) is not null then (c.netamt - d.paidamount) else 0 end) as remainingamount,
sum(case when d.paidamount is not null then d.paidamount else 0 end) as paidamt
from customerinfo c
left join dailypayments d on c.accno = d.accno
right join partnerinfo p on c.partnerid = p.partnerid
where (d.paiddate is null or (d.paiddate >= '2011-3-15' and d.paiddate <= '2012-6-13')) and  p.manager = 7 group by p.partnerid

从上面的查询我需要从第二个表中没有值的两个表中减去两个值。

为了更好地理解,请参见下图。

pic http://i46.tinypic.com/w1zkp4.jpg

1 个答案:

答案 0 :(得分:13)

使用IFNULL()功能删除case并简化计算:

sum(c.netamt - ifnull(d.paidamount, 0)) as remainingamount,