Laravel sql获取最高记录并获得平均字段值

时间:2017-07-26 07:38:10

标签: php mysql sql laravel laravel-5

我怎样才能获得最佳记录,例如前10名前5名前3名,我试图在我的查询中使用 AVG ,但它会返回人员记录的全部平均值。

SQL

if( !$field ) {
    $select = [
        DB::raw('AVG(sFieldGoalsPercentage) AS sFieldGoalsPercentage'), 
        DB::raw('AVG(sThreePointersPercentage) AS sThreePointersPercentage'), 
        DB::raw('AVG(sTwoPointersPercentage) AS sTwoPointersPercentage')
    ];
}

$player1 = DB::table('person_match_statistics')
    ->where('competitionId', $competitionId)
    ->where('personId', $player1Id)
    ->where('periodNumber', 0)
    ->orderBy('matchId', 'DESC')
    ->select($select)
    ->take($lastGame)
    ->get();

阵列

0 => {#543 ▼
  +"sFieldGoalsPercentage": 0.56
  +"sThreePointersPercentage": 0.5
  +"sTwoPointersPercentage": 0.63
}
1 => {#536 ▼
  +"sFieldGoalsPercentage": 0.4
  +"sThreePointersPercentage": 0.4
  +"sTwoPointersPercentage": 0.4
}
2 => {#539 ▼
  +"sFieldGoalsPercentage": 0.38
  +"sThreePointersPercentage": 0.2
  +"sTwoPointersPercentage": 0.67
}

1 个答案:

答案 0 :(得分:2)

您可以使用avg()收集方法。获得十大记录:

$player1 = DB::table('person_match_statistics')
    ->where('competitionId', $competitionId)
    ->where('personId', $player1Id)
    ->where('periodNumber', 0)
    ->latest('matchId')
    ->select($select)
    ->take(10)
    ->get();

然后使用take()avg()收集方法计算平均值而不执行任何新查询。例如:

$top10 = $player1->avg('column');
$top5 = $player1->take(5)->avg('column');
$top3 = $player1->take(3)->avg('column');