How do I group by day instead of date?

前端 未结 6 1738
情书的邮戳
情书的邮戳 2020-12-03 13:56

ok so i have

 >> list = Request.find_all_by_artist(\"someBand\")
=> [#

        
相关标签:
6条回答
  • 2020-12-03 14:26

    you can use GROUP BY DATE(created_at) in MySQL

    On ruby code you can use like this

    list.group('DATE(created_at)').map {|k,v| [k, v.length]}.sort
    
    0 讨论(0)
  • 2020-12-03 14:29

    There is a gem for that: groupdate.

    Usage (from the docs):

    User.group_by_day(:created_at).count
    # {
    #   2013-04-16 00:00:00 UTC => 50,
    #   2013-04-17 00:00:00 UTC => 100,
    #   2013-04-18 00:00:00 UTC => 34
    # }
    
    0 讨论(0)
  • 2020-12-03 14:34

    Group without extra gems:

    def self.group_by_day items
       data = items.group_by{|x| x.created_at.to_date}
       chart_data = {}
    
       data.each do |a,b|
         chart_data.merge!({a => b.count})
       end
    
       return chart_data
    end
    
    0 讨论(0)
  • 2020-12-03 14:37

    Ipsum's answer is actually good and probably the best:

    In Arel:

    requests = Arel::Table.new(:requests)
    query = requests.project("COUNT(*), CAST(requests.created_at AS DATE) as created_at")
    query = query.group("CAST (requests.created_at AS DATE)")
    Request.find_by_sql(query.to_sql)
    
    0 讨论(0)
  • 2020-12-03 14:42

    I think this is a much more elegant and simple solution

    list.group_by{|x| x.created_at.strftime("%Y-%m-%d")} 
    
    0 讨论(0)
  • 2020-12-03 14:44

    Time is a quite complex object to group by. Assuming you want to group by the creation date, instead of the full Time, start creating a custom method in your model to return the group criteria.

    The method should return the creation date, possibly as string.

    def group_by_criteria
      created_at.to_date.to_s(:db)
    end
    

    Then, group by that method.

    list.group_by(&:group_by_criteria).map {|k,v| [k, v.length]}.sort
    
    0 讨论(0)
提交回复
热议问题