Laravel查询,分组和计数

时间:2018-12-30 06:24:03

标签: php laravel laravel-5 laravel-5.7

我有一个

的表方案

| playerID | team | gameResult | pickOrder |

我有成百上千个结果,我正在尝试找出playerID分组的以下内容。

仅当gameResult的值为Win时,我想计算LosspickOrder还是0的次数。我想以数组格式显示,例如

array(
  'PlayerID' => '2837192',
    'data' => array(
       'win' => '9',
       'Loss' => '3'
      )
   ),
   ...
)

任何帮助将不胜感激。如有任何问题,请告诉我。

1 个答案:

答案 0 :(得分:1)

使用条件聚合:

$results = DB::table('players')
               ->select(DB::raw("playerID"),
                        DB::raw("COUNT(CASE WHEN gameResult = 'Win'  THEN 1 END) AS win_cnt"),
                        DB::raw("COUNT(CASE WHEN gameResult = 'Loss' THEN 1 END) AS loss_cnt"))
               ->where('pickOrder', '=', 0)
               ->groupBy('playerID')
               ->get();

上面的Laravel代码将对应于以下原始MySQL查询:

SELECT
    playerID,
    COUNT(CASE WHEN gameResult = 'Win'  THEN 1 END) AS win_cnt,
    COUNT(CASE WHEN gameResult = 'Loss' THEN 1 END) AS loss_cnt
FROM players
WHERE pickOrder = 0
GROUP BY
    playerId;