首页 > 解决方案 > 具有项目和项目类型分组的列总和

问题描述

我有桌子

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')

有没有办法得到我想要的结果。否则我必须做一个获取请求并遍历每个请求。当表变大时,这可能会导致问题

这种操作叫什么?

标签: phpmysqllaravellaravel-5eloquent

解决方案


您可以使用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')

推荐阅读