开发者

group by + sum on multiple columns in rails 3

I need to get a list of locations ordered by the number of picture that I have in the DB for these l开发者_运维百科ocations, 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?


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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜