我有一个
的表方案 | playerID | team | gameResult | pickOrder |
我有成百上千个结果,我正在尝试找出playerID
分组的以下内容。
仅当gameResult
的值为Win
时,我想计算Loss
是pickOrder
还是0
的次数。我想以数组格式显示,例如
array(
'PlayerID' => '2837192',
'data' => array(
'win' => '9',
'Loss' => '3'
)
),
...
)
任何帮助将不胜感激。如有任何问题,请告诉我。
答案 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;