简体   繁体   English

Laravel如何从每组中获取前3条记录的AVG值

[英]Laravel how to get the AVG value of first 3 records from each group

I have a database table, which includes points against the player. 我有一个数据库表,其中包含针对玩家的分数。 A Single player have multiple records in the table. 单个玩家在表中有多个记录。 I need to group the records by the player_id. 我需要按player_id对记录进行分组。 And I am trying to get the average of first 3 records of the each group. 我正在尝试获取每个组的前3条记录的平均值。 I tried to reach this over the last evening. 我试图在最后一个晚上达到这个目标。 But I had not any luck to solve this. 但是我没有运气来解决这个问题。

This is my initial code, And I need to modify this to get the AVG of first 3 records of each group(grouped by player_id) 这是我的初始代码,我需要对其进行修改以获取每个组的前3条记录的AVG(按player_id分组)

$oSelect = DB::table('statistics')
          ->where('statistics.league_id', $league_id)
          ->select('id, AVG('statistics.points as points'),player_id, scheduled')
          ->orderBy('statistics.scheduled','DESC')
          ->groupBy('statistics.player_id');

Thank you in advanced 谢谢高级

Try this: 尝试这个:

$oSelect = DB::table('statistics')
      ->select(DB::raw('id, AVG(statistics.points) as points,player_id,scheduled'))
      ->where('statistics.league_id', $league_id)
      ->orderBy('statistics.scheduled','DESC')
      ->groupBy('statistics.player_id')->limit(3)->get();

Notice: if you get nonaggregated column error that case you must add id column to grouped by columns list or disable the only_full_group_by option in mySql 注意:如果出现非聚合列错误,则必须将id列添加到按列分组的列表中,或禁用mySql中的only_full_group_by选项

Disable ONLY_FULL_GROUP_BY 停用ONLY_FULL_GROUP_BY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM