Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 211
Mohit Jain Avatar asked Aug 20 '11 10:08

Mohit Jain


People also ask

Can I use ORDER BY with count?

ORDER BY COUNT clause in standard query language(SQL) is used to sort the result set produced by a SELECT query in an ascending or descending order based on values obtained from a COUNT function. For uninitiated, a COUNT() function is used to find the total number of records in the result set.

How do you ORDER BY after GROUP BY?

Using Group By and Order By Together When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.

How do you ORDER BY count in SQL?

Use ORDER BY with DESC to order in descending order. For counting the values, use the COUNT(). For example, if the name “John” appears thrice in the column, then a separate column will display the count 3 and in this way all the count values will be arranged in descending order using the ORDER BY DESC.

Can count be used with GROUP BY?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.


1 Answers

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') 
like image 120
Simon Elliston Ball Avatar answered Sep 22 '22 00:09

Simon Elliston Ball