如何使用ActiveRecord进行多次计算

时间:2013-09-16 18:10:07

标签: mysql ruby ruby-on-rails-3 activerecord

我有一个简单的国家/地区表,其中包含姓名,大陆,人口和其他一些字段。

我正在尝试使用ActiveRecord执行以下MySQL查询

SELECT count(*),SUM(人口),AVG(人口)来自大陆='亚洲'的国家

我应该怎么做呢?

我试过了:

Country.where(:continent =>'Asia')。count()

Country.where(:continent =>'Asia')。sum(:population)

Country.where(:continent =>'Asia')。average(:population)

所有工作都很好,他们都返回数字(不是ActiveRelation对象),这意味着你不能做像

这样的事情

Country.where(:continent =>'Asia')。count()。sum(:population).average(:population)

2 个答案:

答案 0 :(得分:3)

找到了解决方案:

result = Country.select(“count(*)as num_countries,sum(population)as total_population,avg(population)as average_population).where(:continent =>'asia')。to_a [0]

允许您随后访问结果: result.num_countries,result.total_population和result.average_population

答案 1 :(得分:0)

您可以尝试:

ActiveRecord::base.connection.execute('SELECT count(*), SUM(population), AVG(population) FROM countries where continent='Asia')

这将返回一个哈希:

{'count(*)': count, ... }