Group + sum for several columns in rails 3

I need to get a list of places ordered by the number of images that I have in the DB for these locations, here is my query

Location.select(:city).group(:city).order("SUM(images_count) DESC").sum(:images_count) 

It worked like a charm, unfortunately, now I need to add a province and a country to prevent ambiguities, so now I have this

 Location.select(:city, :province, :country).group(:city, :province, :country).order("SUM(images_count) DESC").sum(:images_count) 

And this does not work :(

Can someone help me with this request?

+4
source share
2 answers

I'm not very proud of my solution, but it works:

 Location.group(:city, :province, :country) .select(:city, :province, :country, "SUM(images_girl_count) as sum_images_count") .order("sum_images_count DESC") .collect{ |location| [location.city, location.province, location.country, location.sum_images_count] } 

Any feedback?

+18
source

The sum method uses only one column when grouping, try the following:

 Location.select(:city, :province, :country, "SUM(images_count) as sum_images_count").group(:city, :province, :country).order("sum_images_count DESC") 

Perhaps this is the best way.

I hope this helps.

+2
source

Source: https://habr.com/ru/post/1337849/


All Articles