如何将复杂的嵌套联接sql查询转换为活动记录rails 3?

如何将复杂的嵌套联接sql查询转换为活动记录rails 3?,sql,ruby-on-rails,ruby,activerecord,Sql,Ruby On Rails,Ruby,Activerecord,我创建了一个SQL查询并成功运行了它。此查询返回每个组中具有最后一次事务处理时间的记录 Select s.id, s.location_id From sales_transactions s INNER JOIN ( Select location_id, MAX(transaction_time) AS lastest From sales_transactions Group By location_id) s1 ON s.

我创建了一个SQL查询并成功运行了它。此查询返回每个组中具有最后一次事务处理时间的记录

Select s.id, s.location_id 
From sales_transactions s 
    INNER JOIN (
        Select location_id, MAX(transaction_time) AS lastest 
        From sales_transactions 
        Group By location_id) s1 
ON s.location_id = s1.location_id     
   AND s1.lastest = s.transaction_time
我使用ActiveRecord::Base.connection.execute成功运行上述查询。现在,我想将这个SQL查询转换为Rails3中的活动记录查询。我在这里搜索了很多问题,但是,由于子查询中的聚合函数,我找不到解决方案

你可以做:

SalesTransaction.select('id', 'location_id', 'max(transaction_time) AS lastest').group(:location_id)
或者略有不同但结果相同(加上更快):


我尝试了,但它返回了错误:“ActiveRecord::StatementInvalid:PG::error:error:column“sales\u transactions.id”必须出现在GROUP BY子句中或在聚合函数中使用。请提供您的模型和架构。
SalesTransaction.order(:transaction_time).group(:location_id)