gpt4 book ai didi

mysql - 查询获取列总计并减去 MySQL

转载 作者:行者123 更新时间:2023-11-29 17:49:17 24 4
gpt4 key购买 nike

我有一个交易表

我可以使用这些查询分别获取按属性(property)划分的所有借方和贷方交易总额

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

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

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

有什么办法可以实现这个目标吗?

最佳答案

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

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

关于mysql - 查询获取列总计并减去 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525969/

24 4 0
文章推荐: python - 属性错误: 'function' object has no attribute 'encode' error when writing to MySQL database
文章推荐: android - ViewPager 显示重复 View
文章推荐: javascript - 未捕获的类型错误 : Object # has no method 'vibrate'