使用Active Record的Rails GROUP BY查询

时间:2019-07-15 13:33:16

标签: ruby-on-rails activerecord ruby-on-rails-5 rails-activerecord ruby-on-rails-5.2

我想使用经典的Active Record而不是原始sql编写此查询。

SELECT

   user_id,
   term, 
   SUM(views) AS Views,
   SUM(clicks) AS Clicks

FROM reports
GROUP BY user_id, term

尝试过此方法,但不起作用。

Report.group([:user_id, :term]).sum([:views, :clicks])

我知道可以使用.group_by {},但效率不是很高,因为它是由Ruby聚合的,并不执行查询。

DB:PostgreSQL

1 个答案:

答案 0 :(得分:2)

我认为您可以使用此

@reports = Report.select("reports.user_id, reports.term,
  sum(reports.views) as total_views
  sum(reports.clicks) as total_clicks").
  group("reports.user_id, reports.term")

请注意全部(作为总和),尽管它们没有显示,但是如果您叫该名字,它们确实存在

@report.first # total_views and total_clicks not show up in rails console but
@report.first.total_views # you will see total calculation