我有一个 Company
模型,has_many
Statement
。
class Company < ActiveRecord::Base
has_many :statements
end
我想获取具有按 fiscal_year_end
字段分组的最新 date
字段的 statements
。
我实现了这样的功能:
c = Company.first
c.statements.to_a.group_by{|s| s.fiscal_year_end }.map{|k,v| v.max_by(&:date) }
它工作正常,但如果可能的话我想使用 ActiveRecord 查询(SQL),这样我就不需要将不必要的实例加载到内存中。
如何使用SQL编写?
最佳答案
select t.username, t.date, t.value
from MyTable t
inner join (
select username, max(date) as MaxDate
from MyTable
group by username
) tm on t.username = tm.username and t.date = tm.MaxDate
关于ruby-on-rails - 如何使用 SQL 获取按年份分组的最新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41345467/