查询以获取列总计和减去MySQL

时间:2018-03-28 04:11:17

标签: mysql database select transactions subquery

我有一个交易表

我可以使用这些查询单独获取所有借记和贷记交易总额

SELECT property, SUM(amount) as creditamount FROM transactions WHERE transactions.type="CREDIT" GROUP BY property    

SELECT property, SUM(amount) as debitamount FROM transactions WHERE transactions.type="DEBIT" GROUP BY property

我在单个查询中完成这两个查询时遇到困难,这样我就可以减去每行的信用额度和借方金额,并根据属性列出

我尝试使用子查询但返回了多行。

有任何方法可以达到这个目的吗?

2 个答案:

答案 0 :(得分:0)

使用自助加入

select debitamount , creditamount
from (select sum(amount) income
     from  transactions 
     WHERE transactions.type="CREDIT"  
     GROUP BY property) i
JOIN (select sum(rate) debitamount 
     from transactions 
     WHERE transactions.type="DEBIT" 
     GROUP BY property) e

参考this question

答案 1 :(得分:0)

您可能正在寻找条件聚合。

SELECT property, 
 SUM(case when type = 'Credit' then amount else 0 end) as creditamount,
 SUM(case when type = 'Debit' then amount else 0 end) as debitamount,
 SUM(case when type = 'Credit' then amount else 0 end) -
 SUM(case when type = 'Debit' then amount else 0 end) as  diff
 FROM transactions 
 GROUP BY property