[英]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 locations, here is my query 我需要得到一个按照我在DB中为这些位置的图片数排序的位置列表,这是我的查询
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 : sum方法在分组时只使用一列,试试这个:
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. 我希望它会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.