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 を使用しました。さて、この SQL クエリを Rails 3 の 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 に答える