简体   繁体   English

Ruby On Rails用sum和group查询?

[英]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. 我想知道如何查询PostgreSQL数据库,它返回一个排行榜。 In other words the sum of points_earned for each user, sorted from first to last? 换句话说,每个用户的points_earned总和,从头到尾排序?

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 这应该返回给你一个前20名用户的列表,这些用户的point_earned降序最多

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. 以下查询适用于mysql和postgress。

Vote.         joins(:user).
              select('users.*, sum(points_earned) as total').
              group('user_id').
              order('total DESC').
              limit(20)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM