Davd_R
Davd_R

Reputation: 384

How to group by a range of values in ActiveRecord (ruby on rails)?

I have an ActiveRecord model that has two columns I want to group and sum by (both are integers). The issue I can't seem to solve is how to sum the first column as a group of the second column, with the second column being grouped by a range.

I know that I can do Model.sum(:first_column, group: :second_column), but this results in many groups, because the second columns values are spread out. How can I group the second columns' values, e.g. in ranges of 10 (0-9, 10-19, 20-29, etc.)?

Upvotes: 3

Views: 1527

Answers (1)

mu is too short
mu is too short

Reputation: 434665

You can GROUP BY expressions in SQL, you don't have to GROUP BY just a column. You can do things like this:

Model.sum(:first_column, :group => 'second_column / 10')

or like this:

Model.group('second_column / 10').sum(:first_column)

Both of those should send some SQL like this into the database:

select sum(first_column), second_column / 10
from models
group by second_column / 10

There will be aliases, quoting, ... but the effect will be the same.

Upvotes: 5

Related Questions