最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

取最小最大的每个组中的ActiveRecord

SEO心得admin52浏览0评论
本文介绍了取最小/最大的每个组中的ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是给定一个表带有属性的类型,品种和价格一个古老的问题,你取纪录的最低价格为每一种存在。

在SQL中,我们可以做的这个通过:

选择f.type,f.variety,f.price 从(选择类型,分(价格)为minprice从表中按类型)为x 内部连接表为f上f.type = x.type和f.price = x.minprice;`

我们也许可以模仿这种方式:

minprices = Table.minimum(:价格,:组=>类型) 结果= [] minprices.each_pair做| T,P |    结果<< Table.find(:第一,:条件=> [?类型=价=,T,P]) 结束

有没有更好的实现比这个?

解决方案

Table.minimum(:价格,:组=>:型)

请参阅api.rubyonrails/classes/ActiveRecord/Calculations/ClassMethods.html更多。

This is an age-old question where given a table with attributes 'type', 'variety' and 'price', that you fetch the record with the minimum price for each type there is.

In SQL, we can do this by:

select f.type, f.variety, f.price from ( select type, min(price) as minprice from table group by type ) as x inner join table as f on f.type = x.type and f.price = x.minprice;`

We could perhaps imitate this by:

minprices = Table.minimum(:price, :group => type) result = [] minprices.each_pair do |t, p| result << Table.find(:first, :conditions => ["type = ? and price = ?", t, p]) end

Is there a better implementation than this?

解决方案

Table.minimum(:price, :group => :type)

See api.rubyonrails/classes/ActiveRecord/Calculations/ClassMethods.html for more.

发布评论

评论列表(0)

  1. 暂无评论