哪个名字最常用?

时间:2014-11-03 08:21:41

标签: ruby

我正在使用rails网站上的ruby,我想检查其数据库中注册用户中最常用的名称。

有一行名为"名字"我会经历的。我现在不介意区分大小写。

任何方便的方式,例如检查什么是最流行的名称,然后第二个最受欢迎,第三最受欢迎等等?

我想到的是让所有用户都在一个数组中然后执行@ users.each do | user |,然后将这些名称记录在一个数组中,之后计算每个记录中包含多个元素的重复项记录。我不确定它是否正确。

3 个答案:

答案 0 :(得分:4)

以下是使用ActiveRecord

执行此操作的方法
User.group(:first_name).order('popularity desc').pluck(:first_name, 'count(*) as popularity')

此代码转换为SQL:

SELECT "users.first_name", count(*) as popularity FROM "users"
GROUP BY first_name
ORDER BY popularity

你会得到类似的东西:

[["John", 2345], ["James", 1986], ["Sam", 1835], ...]

如果您只想要前十名,只需添加limit即可限制结果数量:

User.group(:first_name).order('popularity desc').limit(10).pluck(:first_name, 'count(*) as popularity')

另一种选择是使用count API:

User.group(:first_name).count
=> {"Sam" => 1835, "Stefanos" => 2, ...}

# ordered
User.group(:first_name).order('count_all desc').count
=> {"John" => 2345, "James" => 1986, "Sam" => 1835, ...}

# top 3
User.group(:first_name).order('count_all desc').limit(3).count
=> {"John" => 2345, "James" => 1986, "Sam" => 1835 }

答案 1 :(得分:1)

您可以执行以下SQL语句

select count(*) as count from users group by users.first_name order by count desc

将返回最高的结果。正如鲍里斯所说,只使用sql是正确的方法。

否则,如果您想加载所有用户,可以通过map-reduce。

来加载
@users.group_by(&:first_name).sort(&:count).reverse

将为您提供按名称降序排序的用户数组。

答案 2 :(得分:1)

使用ActiveRecord的另一种方式:

User.group(:first_name).count

生成的SQL是:

SELECT COUNT(*) AS count_all, name AS name FROM `users` GROUP BY name

将输出{name =>的哈希值number_of_occurances}例如

{"John" => 29, "Peter" => 87, "Sarah" => 2}