php - Laravel sql 获取顶部记录并获取其字段值平均值

标签 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
}

最佳答案

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

关于php - Laravel sql 获取顶部记录并获取其字段值平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45320412/

相关文章:

php - 数据未从 Bootstrap Modal 插入 phpMyAdmin 数据库 PHP MySQL

java - 使用 getJdbcTemplate.query(sql,new Object[],rowmapper)) 时如何使用 union 运算符设置 sql 查询的参数?

mysql - SQL:如何总结几十年的计数?

php - laravel 范围函数中的多个查询

php - 两个 mysql 查询似乎比一个查询快,任何人都知道如何在没有开销的情况下组合这些查询?

php - 将变量中的两个值相乘

php - 将 mysqli 结果存储到数组中,然后用 while 循环打印它

php - 始终获得正确的日期时间?

sql - 1条记录如何存储亲属关系信息

php - Yii:根据动态数量限制cgridview中cCheckboxColumn下的复选框选择