带有 sum 和 group 的 Ruby On Rails 查询? [英] Ruby On Rails Query with sum and group?

查看:50
本文介绍了带有 sum 和 group 的 Ruby On Rails 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下模型:

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 数据库.换句话说,每个用户获得的积分总和,从头到尾排序?

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?

到目前为止我有:

Votes.sum(:points_earned).group(:user_id, :id).order(:points_earned)

提前致谢

推荐答案

解决方案

以下查询适用于 mysql 和 postgress.

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)

这篇关于带有 sum 和 group 的 Ruby On Rails 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆