取最小/最大的每个组中的ActiveRecord [英] Fetching Minimum/Maximum for each group in ActiveRecord

查看:100
本文介绍了取最小/最大的每个组中的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(:价格,:组=>:型)
 

请参阅<一href="http://api.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html">http://api.rubyonrails.org/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 http://api.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html for more.

这篇关于取最小/最大的每个组中的ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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