Click here to Skip to main content
16,004,727 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi all...

i want get SUM of values from same table but two different conditions in mysql, the sample table is here...

 --------------------------------------
  credit_id | debit_id | Amount         
 --------------------------------------
|  1           4          10           |
|  1           3          10           |
|  1           2          10           |
|  2           1          20           |
|  3           1          20           |
|  5           1          20           |
----------------------------------------


step1:
First get the SUM(Amount) where credit_id=`1`;
The result is 30.

step2:
Second get the SUM(Amount) where debit_id=`1`;
The result is 60.

step3:
The final step is step2 - step1
That is 60-30=30.


How to get this result in single MySql query..
please help me....
Posted
Updated 23-Nov-13 20:34pm
v2

select (select sum(Amount) from table3 where debit_id ='1') - (select sum(Amount) from table3 where credit_id ='1') 
 
Share this answer
 
Comments
sv sathish 24-Nov-13 2:00am    
Thank you sir:)
Peter Leow 24-Nov-13 2:04am    
You are welcome.
sv sathish 24-Nov-13 2:32am    
Sir i want another help
You See the same table,the credit_id=5 means the result is NULL.
i want the result,For example the credit_id is 5 then

SUM(Amount) where credit_id=`5` - SUM(Amount) where debit_id=`5`;
i expected result is 20...
how it's possible...
Just back from a jog, a quick solution here:

SQL
select (select sum(amount) from table3 where credit_id ='5') -
(SELECT IF((select count(*) from table3 WHERE debit_id='5') > 0, (select sum(amount) from table3 where debit_id ='5'), 0))
 
Share this answer
 
Comments
sv sathish 24-Nov-13 9:00am    
Thank you so mush sir;)

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