Group, count, having, and order by in Rails

Don P picture Don P · Jan 7, 2015 · Viewed 17.1k times · Source

I have a table: people with a column named: age.

How can I get a count of the people with each age, ordered from oldest to youngest, filtered by ages with at least 2 people in it?

How I would write it in raw SQL:

SELECT
  COUNT(1) AS people_count,
  age
FROM people
GROUP BY age
HAVING people_count > 1
ORDER BY age DESC

In Rails (I'm not sure how to do it):

Person.group(:age).count will get me the counts by age, but I can't figure out how to order it descendingly by age, or add the having clause.

Answer

eugen picture eugen · Jan 7, 2015

Try something like:

Person.select("id, age").group(:id, :age).having("count(id) > 1").order("age desc")