2013-06-19 78 views
0

我創建了一個SQL查詢併成功運行它。此查詢返回每個組中具有最後一個transaction_time的記錄。如何將複雜的嵌套連接sql查詢轉換爲Active Record rails 3?

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查詢。但是,我在這裏搜索了很多問題,因爲我的子查詢中的聚合函數找不到解決方案。

回答

0

你可以這樣做:

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

或相同的結果有點不同,但(加上更快):

SalesTransaction.order(:transaction_time).group(:location_id) 
+0

我想,它會返回錯誤:「的ActiveRecord :: StatementInvalid:PG: :錯誤:錯誤:列「sales_transactions.id」必須出現在GROUP BY子句中或用於聚合函數中「。 – VDVinh

+0

請提供您的模型和模式。 – wintermeyer

相關問題