I have a table which contains hourly records (spanning multiple days). What I’d like to do is get the last hourly record for each day.
I found the MySQL solution here: Retrieving the last record in each group (the accepted answer looks good to me, and more or less makes sense)
However, I’m struggling to implement this with Rails finders, since it’s unclear how to do a self join in Rails (all of the documentation applies to association).
So far I’ve tried this… but to no avail (it says the “id” column is ambiguous).
Report.joins("LEFT JOIN reports r2 ON (date('created_at') = date('r2.created_at') AND id < r2.id)").where("r2.id IS NULL")
You probably just need to explicitly reference your
reportstable in the SQL:For a more “Railsey” way to achieve this, you might want to look at the
finder_sqloption tohas_manyand create an association to do this.