问题
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