开发者

Is it possible to group by hour/minute/quarter hour directly in ActiveRecord/Rails?

开发者 https://www.devze.com 2023-01-12 05:07 出处:网络
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?

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 开发者_Go百科  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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号