Ruby On Rails用sum和group查询?
鉴于以下模型:
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
我想知道如何查询PostgreSQL数据库,它返回一个排行榜。 换句话说,每个用户的points_earned总和,从头到尾排序?
到目前为止我有:
Votes.sum(:points_earned).group(:user_id, :id).order(:points_earned)
提前致谢
这应该返回给你一个前20名用户的列表,这些用户的point_earned降序最多
Vote. joins(:user). select('*, sum(points_earned) as total'). group('user_id'). order('total DESC'). limit(20)
解
以下查询适用于mysql和postgress。
Vote. joins(:user). select('users.*, sum(points_earned) as total'). group('user_id'). order('total DESC'). limit(20)