0

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")
Community
  • 1
  • 1
CambridgeMike
  • 4,562
  • 1
  • 28
  • 37

1 Answers1

3

You probably just need to explicitly reference your reports table in the SQL:

Report.joins("LEFT JOIN reports r2 ON (date('reports.created_at') = date('r2.created_at') AND reports.id < r2.id)").where("r2.id IS NULL")

For a more "Railsey" way to achieve this, you might want to look at the finder_sql option to has_many and create an association to do this.

Brandan
  • 14,735
  • 3
  • 56
  • 71
  • That did the trick! thank you, +1 for the finder_sql trick. I'll probably end up implementing it that way. pretty nice! – CambridgeMike Apr 20 '12 at 15:12