Counting and grouping at the same time

后端 未结 4 1985
轻奢々
轻奢々 2020-12-08 01:39

I have a Mail model with the following schema:

t.string   \"mail\"
t.integer  \"country\"
t.boolean  \"validated\"
t.datetime \"created_at\"
t.d         


        
相关标签:
4条回答
  • 2020-12-08 01:55

    With Rails 3 you can simplify it further:

    Mail.where(validated: true).count(group: :country)
    

    You can order by fields in the group - in this case only :country would be valid:

    Mail.where(validated: true)
        .order(:country)
        .count(group: :country)
    

    You can also order by the count, using "count_all":

    Mail.where(validated: true)
        .order("count_all desc")
        .count(group: :country)
    

    You can also limit the number of groups returned. To do this you must call limit before calling count (because #count returns ActiveSupport::OrderedHash):

    Mail.where(validated: true)
        .order("count_all desc")
        .limit(5)
        .count(group: :country)
    

    Updated syntax for Rails 4:

    Mail.where(validated: true)
        .group(:country)
        .count
    
    0 讨论(0)
  • 2020-12-08 02:03
    Mail.find(
        :all, 
        :select => 'count(*) count, country', 
        :group => 'country', 
        :conditions => ['validated = ?', 't' ], 
        :order => 'count DESC',
        :limit => 5)
    

    This should give you records that have a country attribute and a count attribute.

    0 讨论(0)
  • 2020-12-08 02:04

    Try:

    Mail.count(:group => 'country', :conditions => ['validated = ?', 't'])

    I'm not sure count accepts :limit though.

    EDIT:

    I think this is more readable:

    Mail.count(:group => :country, :conditions => {:validated => true})

    0 讨论(0)
  • 2020-12-08 02:09

    I too had to group data with city name and showing count of how many rows are there for each city with specific condition. So this is how I did:

    CityData.where(:status => 1).group(:city_name).count
    

    Output of this was:

    {:Mumbai => 10, :Dublin => 7, :SF => 9}
    
    0 讨论(0)
提交回复
热议问题