帮助在 Ruby on Rails 中对记录进行排序 [英] Help with sorting records in Ruby on Rails

查看:42
本文介绍了帮助在 Ruby on Rails 中对记录进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列的分数表:user_idscore

I have a score table that contains two columns: user_id and score

user_id   分数
1           200
1           120
1           230
2          300
2          345
3           100
3           40
4          350
4           500
......

user_id    score
1               200
1               120
1               230
2               300
2               345
3               100
3               40
4               350
4               500
......

Score.order('score DESC').limit(3) 列出前 3 个分数.相反,如果每个用户只能在列表中获得一个位置(他们的最高分),我将如何获得前 3 个分数.

Score.order('score DESC').limit(3) lists the top 3 scores. Instead, how would I get the top 3 scores where each user only gets one spot on the list (their highest score).

上表中的高分是:

user_id:4 分:500
user_id:2 得分:345
user_id:1 分:230

user_id: 4 score: 500
user_id: 2 score: 345
user_id: 1 score: 230

谢谢!

蒂姆

推荐答案

您应该能够对您的查询进行分组:

You should be able to group your query:

Score.order('score DESC').group('user_id').limit(3)

这篇关于帮助在 Ruby on Rails 中对记录进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆