I created a SQL query and ran it successfully. This query returns the record that has the last transaction_time in each group.
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
I used ActiveRecord::Base.connection.execute to run above query successfully. Now, I want to convert this SQL query into Active Record query in Rails 3. I did searched many questions here, however, because of the aggregate function in my sub query I can't find the solution.
You could do:
SalesTransaction.select('id', 'location_id', 'max(transaction_time) AS lastest').group(:location_id)
or a little bit different but the same result (plus faster):
SalesTransaction.order(:transaction_time).group(:location_id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.