Group and count in Rails

后端 未结 7 1929
傲寒
傲寒 2021-02-01 12:06

I know I\'ve seen this before but I can\'t find anything now. I want to group a query by a certain column and be able to display how many are in each group. I got the first part

相关标签:
7条回答
  • 2021-02-01 12:35

    something like

     User.all(:joins => :comments, :select => "users.*, count(comments.id) as comments_count", :group => "users.id")
    

    might also work...

    0 讨论(0)
  • 2021-02-01 12:41

    I think you can try this as well.

    @project.line_items.group(:device_id).pluck("device_id, count(device_id)")
    

    ^^ This gives array of arrays with elements 'device_id and count'

    0 讨论(0)
  • 2021-02-01 12:44

    hash of devise_id as key and associated records count

    @project.line_items.group(:device_id).count
    
    0 讨论(0)
  • 2021-02-01 12:48

    Just add a :select option:

    @line_items = @project.line_items.all(
      :group  => "device_id",
      :select => "device_id, COUNT(*) as count"
    )
    

    Then each @line_item will have a count attribute.

    0 讨论(0)
  • 2021-02-01 12:50

    You can do count on line_items which will return you an ordered hash of device_id and count.

    @project.line_items.group(:device_id).count
    
    0 讨论(0)
  • 2021-02-01 12:56

    For only count pluck would be faster here rather than group

    @project.line_items.pluck(:device_id).count
    
    
    @project.line_items.pluck(:device_id).uniq.count
    
    0 讨论(0)
提交回复
热议问题