You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL中如何按book_name分组计算(debit总和-credit总和)的聚合值?

解决MySQL中按分组计算 debit总和 - credit总和的问题

没问题,这其实可以通过条件聚合函数轻松实现,核心思路就是分别统计每个分组下debit和credit的总额,再做差值计算。

具体SQL语句

SELECT 
    book_name,
    SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END) - 
    SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE 0 END) AS balance
FROM 
    your_table_name
GROUP BY 
    book_name;

语句解释

  • SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END):只对transaction_type为debit的记录求和,其他情况计为0,得到每个分组的debit总额。
  • SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE 0 END):同理,得到每个分组的credit总额。
  • 两者相减就得到你需要的debit总和 - credit总和的结果,用AS balance给结果列起个清晰的别名。
  • GROUP BY book_name确保按书名分组计算。

测试结果

把你的数据代入这个查询,会得到:

book_namebalance
demo-80
testing-20

完全符合你的预期结果。

另外还有一种简化写法,用IF函数替代CASE,逻辑完全一致,代码更简洁:

SELECT 
    book_name,
    SUM(IF(transaction_type = 'debit', amount, 0)) - 
    SUM(IF(transaction_type = 'credit', amount, 0)) AS balance
FROM 
    your_table_name
GROUP BY 
    book_name;

两种写法在MySQL里都能正常运行,选你觉得更易读的就行。

内容的提问来源于stack exchange,提问作者Juggernaut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:36:56