GROUP BY +多列轨道3总和 [英] group by + sum on multiple columns in rails 3

查看:203
本文介绍了GROUP BY +多列轨道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)

这工作就像一个魅力,不幸的是,我现在需要添加全省乃至全国prevent含糊不清的出现,所以我现在有这个

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] }

任何意见?

这篇关于GROUP BY +多列轨道3总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆