Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am having a table in mysql like this

Table1 name: credit
Date          Company Name        Amount
2013-12-11    smevc               500
2013-12-21    smevc               500
2013-12-21    smevc               1000
2013-12-21    smevc               6726
2013-12-21    smevc               8354.40
2013-12-20    smevc               700
2013-12-22    sec                 3736
2013-12-23    ccs                 3000

Table2 name: debit
Date         company_name         deb_amt
2013-12-24   smevc                1000
2013-12-22   smevc                2000
2013-12-22   ccs                  2000

Now i want to take difference calculation here i.e., Amount - deb_amt
Now
I need a output like
comp_name  bal_amt
smevc      14780.40
sec        3736
ccs        1000

Remember sec is available only in table 2 debit.. not in table 1 credit..
I got the output but the value of sec was displayed as null.
i used this query
SQL
SELECT cm.company_name AS comp_name,
((SELECT SUM(credit_amount) FROM credit_details c WHERE c.company_name = cm.company_name GROUP BY c.company_name) -
(SELECT SUM(debit_amount) FROM debit_details d WHERE d.company_name = cm.company_name GROUP BY d.company_name)) AS bal_amt
FROM credit_details cm GROUP BY cm.company_name
ORDER BY bal_amt DESC


pls correct my query to get the output.
Thanks,
Siva
Posted
Updated 28-Dec-13 22:55pm
v2

1 solution

It's not an elegant solution but it may work...

SQL
select 
c.company,
c.amount - ifnull(d.debit,0) balance
from
(
select 
company,sum(amount) amount
from credit
group by company
)c
left join
(
select 
company, sum(deb_amt) debit
from debit
group by company
)d
on a.company = d.company
 
Share this answer
 
v2
Comments
sivamzcet 29-Dec-13 3:11am    
query works but the company name sec and its balance was not came
GuyThiebaut 29-Dec-13 3:50am    
select
c.company,
c.amount - isnull(d.debit,o) balance
from
(
select
company,sum(amount) amount
from credit
group by company
)c
left join
(
select
company, sum(deb_amt) debit
from debit
group by company
)d
on a.company = d.company
sivamzcet 29-Dec-13 4:39am    
#1582 - Incorrect parameter count in the call to native function 'isnull'
this error was came.. wat to do now??
sivamzcet 29-Dec-13 4:48am    
okay i got.. its ifnull condition not isnull :)
Thanks for your reply
Stay in touch with us :)
GuyThiebaut 29-Dec-13 4:56am    
I have amended the original solution.

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