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

请求编写MySQL查询:按字段值拆分列并计算final_amount(credit-debit)

解决方案:用条件聚合实现行转列

没问题,这需求刚好可以用MySQL的条件聚合来搞定,完美匹配你要的输出格式。首先我先假设你的表名为transactions,字段分别是customer_id(对应你数据里的数字)、transaction_type(对应credit/debit)、amount(对应金额)——如果你的表名或字段名不一样,替换成实际名称就行。

最终SQL查询语句

SELECT
    customer_id,
    SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE 0 END) AS credit,
    SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END) AS debit,
    SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE 0 END) - SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END) AS final_amount
FROM transactions
GROUP BY customer_id;

语句解释

  • SUM(CASE...)是核心逻辑:通过CASE判断交易类型,只累加对应类型的金额,其他情况补0,这样就把分散在多行的credit和debit聚合到同一行的两列里。
  • GROUP BY customer_id确保每个客户只输出一行结果,把该客户的所有交易都聚合起来(哪怕同一个客户有多次credit/debit也能正确计算总和)。
  • final_amount也可以简化写法:SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE -amount END) AS final_amount,和原写法效果完全一致,看你习惯哪种就用哪种。

测试验证

如果把你给的原始数据插入表中:

INSERT INTO transactions (customer_id, transaction_type, amount)
VALUES
(3, 'credit', 500.00),
(3, 'debit', 500.00),
(4, 'credit', 300.00),
(4, 'debit', 300.00),
(5, 'credit', 300.00),
(5, 'debit', 300.00),
(6, 'credit', 300.00),
(6, 'debit', 300.00);

运行查询后会得到如下结果:

customer_idcreditdebitfinal_amount
3500.00500.000.00
4300.00300.000.00
5300.00300.000.00
6300.00300.000.00

完全符合你要的输出格式~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:43:38