如何从同一个表中获取两个不同值的SUM [英] how to get SUM of two different values from same table
本文介绍了如何从同一个表中获取两个不同值的SUM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好...
i希望从同一个表中得到SUM值,但在mysql中有两个不同的条件,示例表就在这里...
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:
首先得到 SUM(金额),其中credit_id =`1`;
结果是30.
step2:
第二次得到 SUM(金额)其中debit_id =`1`;
结果是60.
step3:
最后一步是 step2 - step1
即60-30 = 30.
如何在单个MySql查询中获得此结果..
请帮助我....
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....
推荐答案
select (select sum(Amount) from table3 where debit_id ='1') - (select sum(Amount) from table3 where credit_id ='1')
刚从慢跑回来,这里有一个快速解决方案:
Just back from a jog, a quick solution here:
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))
这篇关于如何从同一个表中获取两个不同值的SUM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文