Ruby on rails 3 如何使用Rails 3.0将表与包含聚合函数的子查询连接起来

Ruby on rails 3 如何使用Rails 3.0将表与包含聚合函数的子查询连接起来,ruby-on-rails-3,activerecord,join,aggregate-functions,Ruby On Rails 3,Activerecord,Join,Aggregate Functions,我有一个包含时间戳(time)、股票代码(symbol)和一些其他属性a、b、c等的股票价格表 在SQL中,我将编写以下代码: Select * FROM stock_prices, (SELECT symbol, max(time) as max_time FROM stock_prices GROUP BY symbol) latest_prices WHERE stock_prices.symbol = la

我有一个包含时间戳(time)、股票代码(symbol)和一些其他属性a、b、c等的股票价格表

在SQL中,我将编写以下代码:

Select * 
FROM stock_prices, (SELECT symbol, max(time) as max_time
                    FROM stock_prices
                    GROUP BY symbol) latest_prices
WHERE stock_prices.symbol = latest_prices.symbol
AND stock_prices.time = latest_prices.max_time

我想用rails 3.0 ActiveRecord查询工具select、from、group等来表达这个查询。我该怎么做?

虽然可以混合使用rails方法和SQL片段来实现这一点,但这可能会变得混乱。直接执行这样的复杂查询通常要简单得多

请查看
find_by_sql
方法,以便在模型的上下文中执行此操作: