“按组”计数的“按组”结果?

这个问题

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

会给我一个大杂烩。

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

现在我想按照每个组的计数来排序。我如何在查询中做到这一点。

70810 次浏览

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

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