加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用sum和group查询Ruby On Rails?

发布时间:2020-12-17 03:40:17 所属栏目:百科 来源:网络整理
导读:鉴于以下模型: 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数据库,它返回一个排行榜. 换句
鉴于以下模型:

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读