Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails Query with sum and group?

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

like image 262
ipegasus Avatar asked Feb 16 '23 17:02

ipegasus


2 Answers

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)
like image 192
cryo28 Avatar answered Feb 23 '23 18:02

cryo28


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)
like image 34
ipegasus Avatar answered Feb 23 '23 17:02

ipegasus