同时计数和分组
我有一个带有以下架构的Mail
模型:
t.string "mail" t.integer "country" t.boolean "validated" t.datetime "created_at" t.datetime "updated_at"
我想找到数据库中的前5个国家,所以我继续打字
@top5 = Mail.find(:all,:group => 'country',:conditions => [ "validated = ?" , "t" ], :limit => 5 )
这将告诉我团体(我需要一个订单,我不知道怎么写)
@top5 = Mail.count(:all,:group => 'country',:conditions => [ "validated = ?" , "t" ], :limit => 5 )
这将告诉我每组中有多少邮件
我想知道我是否可以一次性分组和计算
Mail.find( :所有, :select =>'count(*)count,country', :group =>'country', :conditions => ['validated =?','t'], :order =>'count DESC', :limit => 5)
这应该为您提供具有country属性和count属性的记录。
尝试:
Mail.count(:group => 'country', :conditions => ['validated = ?', 't'])
我不确定伯爵是否接受:limit
虽然:limit
。
编辑:
我认为这更具可读性:
Mail.count(:group => :country, :conditions => {:validated => true})
使用Rails 3,您可以进一步简化它:
Mail.where(validated: true).count(group: :country)
您可以按组中的字段排序 – 仅在这种情况下:国家/地区有效:
Mail.where(validated: true) .order(:country) .count(group: :country)
您也可以使用“count_all”按计数订购:
Mail.where(validated: true) .order("count_all desc") .count(group: :country)
您还可以限制返回的组数。 为此,您必须在调用count之前调用limit(因为#count
返回ActiveSupport::OrderedHash
):
Mail.where(validated: true) .order("count_all desc") .limit(5) .count(group: :country)
更新了Rails 4的语法:
Mail.where(validated: true) .group(:country) .count
我也不得不将数据与城市名称分组,并显示具有特定条件的每个城市的行数 。 所以这就是我做的:
CityData.where(:status => 1).group(:city_name).count
输出结果如下:
{:Mumbai => 10, :Dublin => 7, :SF => 9}