3

I want to group my data by the hour/day possibly even to the quarter hour.

Can I do this directly in ActiveRecord or should I just grab all the data and do the aggregation manually?

Table "Checkin":
  Time    NumBikes ChangeBikes
  09:00   5         5
  09:05   6         1
  09:10   10        4
  10:00   6         4
  10:05   8         2
  10:10   16        8

Looking to get something like:
  Time   Sum(ChangeBikes) 
  09:00   10
  10:00   14

Thanks in advance, Chris.

Chris Kimpton
  • 5,546
  • 6
  • 45
  • 72

2 Answers2

2

In case you do not need the quarter hour or as an alternative to this (with some work) (and Chris may have discovered this already since it was long ago) you can try the answer detailed here.

The gist is that you can group by an individual time element-- e.g. group(hour(date_time_field)-- or by a date format:

CheckIn.group("date_format(created_at, '%Y%m%d %H/%M')").count

If you want to add in the quarter hour you could try this and then add in formatting

Community
  • 1
  • 1
ScottJShea
  • 7,041
  • 11
  • 44
  • 67
0

The solution I went for was to create additional columns on the table for the time periods I am after. For the example above, I would add a Time_Hour column with the time rounded down to the appropriate hour. I could then do groupings/analysis on that column to get stats by the hour.

Chris Kimpton
  • 5,546
  • 6
  • 45
  • 72