Skip to content Skip to sidebar Skip to footer

How To Sum A Grouped Column In Arel

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 (

Solution 1:

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

SELECT value, label FROM model_table GROUPBY 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 GROUPBY 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"GROUPBY label 

Post a Comment for "How To Sum A Grouped Column In Arel"