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

眉间皱痕 提交于 2019-12-07 15:37:32

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3491650/is-it-possible-to-group-by-hour-minute-quarter-hour-directly-in-activerecord-rai

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!