帮助在 Ruby on Rails 中对记录进行排序 [英] Help with sorting records in Ruby on Rails
问题描述
我有一个包含两列的分数表:user_id
和 score
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屋!