Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group, count, having, and order by in Rails

Tags:

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.

like image 520
Don P Avatar asked Jan 07 '15 08:01

Don P


2 Answers

Try something like:

Person.select("id, age").group(:id, :age).having("count(id) > 1").order("age desc") 
like image 154
eugen Avatar answered Oct 09 '22 17:10

eugen


I find the other answers didn't work for me. I had to do something like this

Person.group(:age).having('count(*) > 1').order('age desc').count 
like image 45
minh Avatar answered Oct 09 '22 16:10

minh