php - 具有项目和项目类型分组的列总和
问题描述
我有桌子
seller_id, transaction_type, sub_total, total_commission_fee, refund_fee, cancellation_fee
3 transaction_type
payment, cancel, refund
我想获得每个卖家 ID 的 sub_total、total_commission_fee、refund_fee、cancellation_fee 的总和
sample
seller_id transaction_type sub_total total_commission_fee refund_fee cancellation_fee
3 order 40 0 0 0
4 order 10 0 0 0
3 cancel 0 0 0 3
3 refund 28 0 2 0
我想要这样的结果
seller_id payment_total(sum of all sub_total transaction_type order) cancel_total(sum of all cancellation_fee transaction_type cancel) refund_total (sum of all refund_fee transaction_type refund)
我可以在没有交易类型的情况下获得总计。
Transaction::groupBy('seller_id')
->selectRaw('sum(sub_total) as total, seller_id')
有没有办法得到我想要的结果。否则我必须做一个获取请求并遍历每个请求。当表变大时,这可能会导致问题
这种操作叫什么?
解决方案
您可以使用IF(condition, value_if_true, value_if_false)
对值求和:
Transaction::groupBy('seller_id')
->selectRaw('SUM(IF(transaction_type = "order", sub_total, 0)) AS payment_total,
SUM(IF(transaction_type = "cancel", cancellation_fee, 0)) AS cancel_total,
SUM(IF(transaction_type = "refund", refund_fee, 0)) AS refund_total,
seller_id')
推荐阅读
- mysql - 如何提高mysql中大文本的查询速度
- powershell - 是否可以使用 Powershell 编辑 Linux 服务器的配置文件?
- java - 测试类/客户端代码中的语法错误
- java - 如何在滑动窗口中删除重复项 - Apache Beam
- node.js - 谷歌云平台,从命令行控制台运行脚本
- vb.net - FindMimeFromData 函数在某些机器上给出不正确的结果
- go - go run 使用旧版本的子包
- wordpress - 如何在 wordpress 中激活子主题?
- wpf - 无法在实时图表中设置 Y 轴的对数刻度
- node.js - 从nodejs中的父目录文件导入变量