获取ActiveRecord中每个组的最小/最大值

11 activerecord group-by aggregate-functions minimum

这是一个古老的问题,给定一个具有属性"类型","变化"和"价格"的表格,您可以获取每种类型的最低价格的记录.

在SQL中,我们可以做这样的:

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;`
Run Code Online (Sandbox Code Playgroud)

我们也许可以通过以下方式模仿:

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

有没有比这更好的实施?

Avd*_*vdi 12

Table.minimum(:price, :group => :type)
Run Code Online (Sandbox Code Playgroud)

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-minimum更多信息,.

  • 如何获得每种类型的最高和最低价格? (2认同)