开发者

activerecord custom aggregate

Let's consider an image table with columns (id, location_id, created_at, counter_1, counter_2), the following query works fine: and it gives me the most recent picture for each location_id:

Image.where(:created_at => Image.maximum(:created_at, :group => :location_id).values)

But now I would like, for each location, t开发者_运维百科he image which has the maximum (counter_1 + 3*counter_2) and the following query does not work (and is semantically wrong, but just to explain what I want to achieve):

Image.where("counter_1 + 3*counter_2" => Image.maximum("counter_1 + 3*counter_2", :group => :location_id).values)

I understand why this does not work, but I don't know how to turn it around and make it work. Is there a way I can define a custom aggregate function? Any other idea?


try this

Image.group(:location_id).order("(counter_1 + 3*counter_2) DESC")

upd

Image.select("*, (counter_1 + 3*counter_2) as counter").group(:location_id).order("counter DESC")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜