我有一个交易表
我可以使用这些查询单独获取所有借记和贷记交易总额
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
我在单个查询中完成这两个查询时遇到困难,这样我就可以减去每行的信用额度和借方金额,并根据属性列出
我尝试使用子查询但返回了多行。
有任何方法可以达到这个目的吗?
答案 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
答案 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