Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i had 3 tables with joining.
when i am subtracting a value from null value, the result was null, but it is not correct.

for a better understanding see the below image and query

http://i46.tinypic.com/w1zkp4.jpg[^]

VB
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
Posted

1 solution

I believe the issue in your code is in this statement here:
SQL
case when (c.netamt - d.paidamount) is not null then (c.netamt - d.paidamount) else 0

This will always be zero when either c.netamt or d.paidamount is zero. Null is not zero, so you cannot subtract from it or with it. What I would recommend, as a first step, would be as follows:
SQL
COALESCE(c.netamt, 0) - COALESCE(d.paidamount,0)

The final code would look like this:
SQL
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(COALESCE(c.netamt, 0) - COALESCE(d.paidamount,0)) 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

However, I'm not a fan of doing calculations inside a SUM statement. I would rather see you do a SELECT statement that got every record and did the calculations on it. Then make that a sub-query of a statement that did the SUMS on each column and grouped by the partnerid. That should make things clearer and more performant.

Also, I used the COALESCE statement instead of the CASE statement. COALESCE returns the first non-null value. It is cleaner than what you are doing and MySQL supports it. It should make your life easier.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900