如何从数据库中获取有序,有限和分组的计数?

时间:2014-12-28 21:42:08

标签: ruby-on-rails rails-activerecord

问题有一个名为主题的列。

人们可以从现有列表中分配问题,例如" Ruby on Rails"," Javascript"等。

如何获得每个问题存在多少主题的降序和限制计数?

期望的结果:

{"Ruby on Rails" => 530,
"Javascript" => 509,
"Node.jS" => 483}

SQL:

SELECT 
  COUNT(1) as questions_with_topic, 
  topic
FROM questions
GROUP BY topic
ORDER BY questions_with_topic DESC
LIMIT 10

Rails :(我不知道如何订购或限制它)

Question.group(:topic).count

1 个答案:

答案 0 :(得分:1)

Question.limit(10).group(:topic).order(:topic).count

按“主题ASC”命令。

要明确指定订单方向,您可以执行以下操作:

Question.limit(10).group(:topic).order("topic DESC").count

按顺序排序,请执行以下操作:

Question.limit(10).group(:topic).order("COUNT(*) ASC").count