How to sum a grouped column in AREL

喜夏-厌秋 提交于 2020-01-17 05:58:45

问题


in Rails 3/AREL

Model.group(:label).sum(:value) will do

SELECT sum(value), label from model_table group by label

I am trying to find the AREL way of doing

SELECT sum(value) from (select value, label from model_table group by label)

which is Model.group(:label).map(&:value).sum using ruby to sum, how do I do this in SQL/AREL


回答1:


Not sure this makes sense. Your core SQL is not valid:

SELECT value, label FROM model_table GROUP BY label

You cannot have a GROUP BY without an aggregation function (e.g. SUM) in your select. I think what you actually want is this:

SELECT label, SUM(value) from model_table GROUP BY label

Am I right? To do this in AREL, try this:

relation = Model.select(:label).
  select(Model.arel_table[:value].sum.as("value_sum")).
  group(:label)
relation.to_sql
# => SELECT label, SUM("model_table"."impressions") AS value_sum FROM "model_table" GROUP BY label 


来源:https://stackoverflow.com/questions/5972336/how-to-sum-a-grouped-column-in-arel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!