group by + sum on multiple columns in rails 3

纵然是瞬间 提交于 2019-12-29 00:40:30

问题


I need to get a list of locations ordered by the number of picture 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)

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

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

And this is not working :(

Could someone help me out with this query?


回答1:


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?




回答2:


The sum method only use one column while grouping, try this :

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

It may be a better way though.

I hope it would help.



来源:https://stackoverflow.com/questions/4855821/group-by-sum-on-multiple-columns-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!