Given the following model:
class Vote < ActiveRecord::Base
attr_accessible :user_id, :vote_for_id, :voting_category_id, ,:points_earned
belongs_to :user
belongs_to :vote_for
belongs_to :voting_category
I would like to know how to make a query for a PostgreSQL DB, that returns a leader-board. In other words the sum of points_earned for each user, sorted from first to last?
So far I have:
Votes.sum(:points_earned).group(:user_id, :id).order(:points_earned)
Thanks in advance
This should return to you a list of top-20 users having most points_earned in descending order
Vote.
joins(:user).
select('*, sum(points_earned) as total').
group('user_id').
order('total DESC').
limit(20)
SOLUTION
The following query works on mysql and postgress.
Vote. joins(:user).
select('users.*, sum(points_earned) as total').
group('user_id').
order('total DESC').
limit(20)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With