【问题标题】:How to add where scope to SUM in ActiveRecord?如何在 ActiveRecord 中将 where 范围添加到 SUM?
【发布时间】:2019-11-10 19:06:30
【问题描述】:

我想返回当前季节按mountain_routes.hearts_count 排序的用户。

我已经为此编写了一个方法,但我的问题是用户的所有山路的总和,我只想按给定range中用户山路的总和排序。

def best_of_season
  range = start_date..end_date
  ::Db::User
    .joins(:mountain_routes)
    .where(mountain_routes: { route_type: 'regular_climbing', created_at: range })
    .select('users.id, SUM(mountain_routes.hearts_count)')
    .group('users.id')
    .distinct
    .order('SUM(mountain_routes.hearts_count) DESC')
end

所以问题出在这部分SUM(mountain_routes.hearts_count)。 如何在给定的range 中只放置山路?

我想收到这样的输出:

NAME   | HEARTS in this season
Thomas | 5
Dave   | 3
Erick  | 1

【问题讨论】:

    标签: sql ruby-on-rails ruby postgresql activerecord


    【解决方案1】:

    您可以使用为SUM(mountain_routes.hearts_count) 添加别名并在 order by 子句中使用它:

    ::Db::User
      .joins(:mountain_routes)
      .where(mountain_routes: { route_type: :regular_climbing, created_at: range })
      .select('users.id, SUM(mountain_routes.hearts_count) AS total_mountain_routes_hearts_count')
      .group(:id)
      .order('total_mountain_routes_hearts_count DESC')
    

    您必须首先摆脱 distinct 方法,因为您已经按 users.id 分组。

    【讨论】:

    • 我认为问题仍然存在,因为我们仍然SUM ALL User mountain_routes.hearts_count 并且我们只想在给定日期从mountain_routes 获得hearts_count .但是您的解决方案将解决第二个问题,如何按SUM 的结果排序结果
    猜你喜欢
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    相关资源
    最近更新 更多