“Order by” result of “group by” count?

爱⌒轻易说出口 提交于 2019-12-04 07:29:29

问题


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.


回答1:


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')



回答2:


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')


来源:https://stackoverflow.com/questions/7131109/order-by-result-of-group-by-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!