rails - group by day as well as hour

前端 未结 2 1909
孤独总比滥情好
孤独总比滥情好 2021-01-02 19:56

I want to create an array of the number of items created each hour, each day.

I\'m tracking how people are feeling, so my model is called TrackMood It j

相关标签:
2条回答
  • 2021-01-02 20:11

    For PostgreSQL you can use date_part

    SO-post - Rails & Postgresql: how to group queries by hour?

    0 讨论(0)
  • 2021-01-02 20:28

    1) Instead of grouping on just the hours part of the date you'll need to group part of the date that is relevant i.e. the date up to the hours and not including anything more specific than that. E.g.

    TrackMood.where(mood: "good").group("date_format(created_at, '%Y%m%d %H')").count
    

    2) You're always going to get a hash back from this call even if it doesn't find any groups. If you want to check how many groups there are you can call .size or .count on it.

    0 讨论(0)
提交回复
热议问题