在rails 3中的多列上分组+总和 [英] group by + sum on multiple columns in rails 3
本文介绍了在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
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)
这不起作用:(
有人可以帮我解决这个问题吗?
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] }
有任何反馈吗?
这篇关于在rails 3中的多列上分组+总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文