2012-06-21 103 views
4
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 

從athe上面的查詢我需要從兩個表中減去兩個表中第二個表中沒有值的值。當空值存在時從兩個表中減去兩個值

爲更好地理解看下面的圖像。

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

+0

該字段爲空? – Sebas

回答

9

使用IFNULL()功能刪除case和簡化計算:

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