我有桌子seller_id, transaction_type, sub_total, total_commission_fee, refund_fee, cancellation_fee3 transaction_typepayment, cancel, refund我想获得每个卖家 ID 的 sub_total、total_commission_fee、refund_fee、cancellation_fee 的总和sampleseller_id transaction_type sub_total total_commission_fee refund_fee cancellation_fee3 order 40 0 0 04 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')有没有办法得到我想要的结果。否则我必须做一个获取请求并遍历每个请求。当表变大时,这可能会导致问题这种操作叫什么?
2 回答
慕莱坞森
TA贡献1810条经验 获得超4个赞
您可以使用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')
繁花不似锦
TA贡献1851条经验 获得超4个赞
您可以通过卖家 ID(seller_id)直接与 group 一起使用。请尝试使用以下查询
Transaction::groupBy('seller_id') ->selectRaw('SUM(sub_total) AS payment_total, SUM(cancellation_fee) AS cancel_total, SUM(refund_fee) AS refund_total, seller_id')
- 2 回答
- 0 关注
- 61 浏览
添加回答
举报
0/150
提交
取消