Samer Buna
Samer Buna

Reputation: 9311

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 (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

Upvotes: 1

Views: 6644

Answers (1)

BSM
BSM

Reputation: 169

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 

Upvotes: 2

Related Questions