Can I group by hour / minute / quarter of an hour directly in ActiveRecord / Rails?

I want to group my data by hours / days, maybe even up to a quarter of an hour.

Can I do this directly in ActiveRecord, or should I just capture 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

Thank you, Chris.

+3
source share
2 answers

The solution I went for was to create additional columns in the table for the time periods that I provide them. In the above example, I would add a Time_Hour column with the rounding time to the corresponding hour. Then I could group / analyze this column to get hourly statistics.

0

( ) ( , , , ), .

, - . group(hour(date_time_field) - :

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

, this,

+2

Source: https://habr.com/ru/post/1759846/


All Articles