Reputation: 1533
I have a date field (Model.expires_on
) and I need to group the records by month and get the sum of the Model.amount
field. I can do:
Model.all.group(:expires_on).sum(:amount)
But when I try to group by month I cannot get it. I have tried:
Model.all.group(:expires_on.month).sum(:amount)
Upvotes: 0
Views: 80
Reputation: 29318
For Postgresql this should work
Model.group("date_part('month',expires_on)").select("date_part('month',expires_on) as expiration_month ,sum(amount) as sum_amount")
You may also be able to use depending on your SQL Provider as Postgresql does not have a month function
Model.group("MONTH(expires_on)").select("MONTH(expires_on) as expiration_month,sum(amount) as sum_amount")
The objects in this collection will then respond to expiration_month
and sum_amount
Know that this will combine all months regardless of year
Upvotes: 1