2011-01-31 64 views
4

我需要獲得由我在DB這些地點的圖片數量排序位置的列表,這裏是我的查詢組在軌+上多列和3

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) 

,這是不工作:(

有人能幫助我這個q uery?

回答

18

我不是很驕傲我的解決方案,但它的工作原理:

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

任何反饋?

2

總和方法只使用而分組的一列,試試這個:

Location.select(:city, :province, :country, "SUM(images_count) as sum_images_count").group(:city, :province, :country).order("sum_images_count DESC") 

這可能是雖然更好的辦法。

我希望這會有所幫助。

+0

美麗的它的作品,我曾嘗試,但沒有「作爲...」 – standup75 2011-02-01 17:25:33

+0

它的工作......但是,我沒有在結果中的總和,我很想擁有,我只得到城市, Province,Country,sum_images_count不見了,你知道我怎麼能得到它嗎? – standup75 2011-02-01 17:32:18