这是给定一个表带有属性的类型,品种和价格一个古老的问题,你取纪录的最低价格为每一种存在。
在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]) endIs there a better implementation than this?
解决方案 Table.minimum(:price, :group => :type)See api.rubyonrails/classes/ActiveRecord/Calculations/ClassMethods.html for more.