问题
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