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

编程入门 行业动态 更新时间:2024-10-07 08:22:31
本文介绍了取最小/最大的每个组中的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.

更多推荐

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

本文发布于:2023-11-30 07:35:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649192.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   最小   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!