如何将复杂的嵌套连接sql查询转换为Active Record rails 3?

时间:2013-06-19 11:03:59

标签: sql ruby-on-rails ruby activerecord

我创建了一个SQL查询并成功运行它。此查询返回每个组中具有最后一个transaction_time的记录。

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查询转换为Rails 3中的Active Record查询。我在这里搜索了很多问题,但是,由于我的子查询中的聚合函数,我无法找到解决方案。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

SalesTransaction.select('id', 'location_id', 'max(transaction_time) AS lastest').group(:location_id)

或稍微不同但结果相同(加快):

SalesTransaction.order(:transaction_time).group(:location_id)
相关问题