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

SQL列值求和后拆分不同值至独立列的查询语句改写求助

SQL改写方案

你当前的SQL将fee_description加入了分组维度,导致同个买家、供应商、单据号下的不同费用类型被拆分为多行。要实现一行展示一个单据所有费用的效果,使用*行转列(透视)*逻辑即可,以下是兼容所有关系型数据库的通用写法:

注意:你原SQL存在笔误,buyer表别名定义为b,但关联条件里写的是bu,以下写法已修正该问题。

select
  b.buyer_id,
  v.vendor_id,
  r.report_number,
  sum(r.amount_fee) as 总费用,
  sum(case when f.fee_description = '平台服务费' then r.amount_fee else 0 end) as 平台服务费,
  sum(case when f.fee_description = '配送费' then r.amount_fee else 0 end) as 配送费,
  sum(case when f.fee_description = '佣金' then r.amount_fee else 0 end) as 佣金
  -- 其余费用类型按照上述格式追加即可
from buyer b
join vendor v on v.vendor_id = b.vendor_id
join report r on r.report_num = b.report_num
join fees f on f.report_num = r.report_num
group by b.buyer_id, v.vendor_id, r.report_number

如果使用特定数据库,可采用对应简化语法:

  • MySQL 8.0+、PostgreSQL:可以用filter关键字简化条件聚合,示例:sum(r.amount_fee) filter (where f.fee_description = '平台服务费') as 平台服务费
  • Oracle、SQL Server:可直接用内置的pivot关键字实现行转列,语法更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:15:03