"Order by" result of "group by" count?

Ruby on-RailsRuby on-Rails-3ActiverecordSql Order-By

Ruby on-Rails Problem Overview


This query

Message.where("message_type = ?", "incoming").group("sender_number").count
 

will return me an hash.

OrderedHash {"1234"=>21, "2345"=>11, "3456"=>63, "4568"=>100}

Now I want to order by count of each group. How can I do that within the query.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

The easiest way to do this is to just add an order clause to the original query. If you give the count method a specific field, it will generate an output column with the name count_{column}, which can be used in the sql generated by adding an order call:

Message.where('message_type = ?','incoming')
       .group('sender_number')
       .order('count_id asc').count('id')

Solution 2 - Ruby on-Rails

When I tried this, rails gave me this error

SQLite3::SQLException: no such column: count_id: SELECT  COUNT(*) AS count_all, state AS state FROM "ideas"  GROUP BY state ORDER BY count_id desc LIMIT 3

Notice that it says SELECT ... AS count_all

So I updated the query from @Simon's answer to look like this and it works for me

.order('count_all desc')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMohit JainView Question on Stackoverflow
Solution 1 - Ruby on-RailsSimon Elliston BallView Answer on Stackoverflow
Solution 2 - Ruby on-RailspennerView Answer on Stackoverflow