简体   繁体   English

帮助在Ruby on Rails中对记录进行排序

[英]Help with sorting records in Ruby on Rails

I have a score table that contains two columns: user_id and score 我有一个包含两列的分数表: user_idscore

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

Score.order('score DESC').limit(3) lists the top 3 scores. Score.order('score DESC').limit(3)列出前3个得分。 Instead, how would I get the top 3 scores where each user only gets one spot on the list (their highest score). 相反,我如何获得前3个分数,其中每个用户只获得列表中的一个位置(他们的最高分)。

The high scores from the above table would be: 上表中的高分将是:

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

Thanks! 谢谢!

Tim 蒂姆

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

Score.order('score DESC').group('user_id').limit(3)
Score.all(:order => 'score DESC', :limit => 3, :group => :user_id)

随着新的Arel:

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

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

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