0

我创建了一个 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 成功运行上述查询。现在,我想在 Rails 3 中将此 SQL 查询转换为 Active Record 查询。我确实在这里搜索了很多问题,但是,由于我的子查询中的聚合函数,我找不到解决方案。

4

1 回答 1

0

你可以这样做:

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

或有点不同但结果相同(加上更快):

SalesTransaction.order(:transaction_time).group(:location_id)
于 2013-06-19T11:44:06.523 回答