Help with sorting records in Ruby on Rails

左心房为你撑大大i 提交于 2020-01-01 18:58:09

问题


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

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) 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).

The high scores from the above table would be:

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

Thanks!

Tim


回答1:


You should be able to group your query:

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



回答2:


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

With new Arel:

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


来源:https://stackoverflow.com/questions/4514265/help-with-sorting-records-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!