sql - Eloquent:从所有具有最小时间戳的行中获取 AVG
问题描述
我想从每个类别的每个最小时间戳中获取用户 ID 及其平均分数。这是表结构
技能表
id | user_id | category | score | timestamp**
0....10............a................11........12
1....10............a................10........9
2....10............b................12........10
3....10............c................11........8
4....11............a................8........9
5....11............b................9........10
6....11............c................10........8
7....11............c................15........14
我想得到这样的结果:
user_id | AVG(score)
10........11 (average id: 1,2,3)
11........9 (average id: 4,5,6)
现在我为每个用户使用循环查询
foreach ($userIds as $id){
// in some case I need to get from only specified Ids not all of them
foreach ($category as $cat) {
// get the minimum timestamp's score for each category
$rawCategory = Skill::where("user_id", $id)->where("timestamp", "<=", $start)->where("category",$cat->id)->orderBy("timestamp", "desc")->first();
if($rawCategory){
$skillCategory[$cat->cat_name] = $rawCategory->score;
}
}
//get the average score
$average = array_sum($skillCategory) / count($skillCategory);
}
我想创建更好的 Eloquent 查询来以良好的性能(< 60 秒)获得这样的数据。有没有人遇到过类似的问题并解决了?如果是这样,你能把链接给我吗?谢谢
解决方案
推荐阅读
- angular - Angular 材质:在表格中使用 *ngIf
- mysql - mysql中的多次DELETE没有删除记录
- r - 使用 for 循环在 R 中创建系列 xlsx 文件
- javascript - 公司道具未显示在 withHandler 内部更新
- git - git push -f 将不需要的日志留在 bitbucket 中
- android - adjustPan 结合 EditText inputType="textPassword" 覆盖了 EditText 的一部分
- python-3.x - 加速 Keras LSTM
- java - HTML 表单转 PDF
- java - DFS 里面的一个条件真的让我很困惑
- python - Django 错误:无法使用 ImageField,因为未安装 Pillow