Don P
Don P

Reputation: 63768

How to get an ordered, limited, and grouped count from database?

Questions have a column called topic.

People can assign a question a topic from an existing list like "Ruby on Rails", "Javascript", etc.

How can I get a descending and limited count of how many topics exist for each question?

Desired result:

{"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: (I don't know how to order or limit it)

Question.group(:topic).count

Upvotes: 1

Views: 41

Answers (1)

SHS
SHS

Reputation: 7744

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

That orders by "topic ASC".

To explicitly specify order direction you can do this:

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

And to order by count, do this:

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

Upvotes: 1

Related Questions