在rails 3中的多个列上按+总和
我需要得到一个按照我在DB中为这些位置的图片数量排序的位置列表,这是我的查询
Location.select(:city).group(:city).order("SUM(images_count) DESC").sum(:images_count)
这很像一个魅力,不幸的是,我现在需要添加省和国家,以防止出现歧义,所以我现在有这个
Location.select(:city, :province, :country).group(:city, :province, :country).order("SUM(images_count) DESC").sum(:images_count)
这不起作用:(
有人可以帮我解决这个问题吗?
我不是很自豪我的解决方案,但它的工作原理:
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] }
任何反馈?
sum方法在分组时只使用一列,试试这个:
Location.select(:city, :province, :country, "SUM(images_count) as sum_images_count").group(:city, :province, :country).order("sum_images_count DESC")
这可能是一种更好的方式。
我希望它会有所帮助。