Ruby-on-rails “分组依据”计数的“排序依据”结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7131109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:49:06  来源:igfitidea点击:

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

ruby-on-railsruby-on-rails-3activerecordsql-order-by

提问by Mohit Jain

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.

现在我想按每组的数量排序。我怎样才能在查询中做到这一点。

回答by Simon Elliston Ball

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:

最简单的方法是在原始查询中添加一个 order 子句。如果给 count 方法一个特定的字段,它会生成一个名为 count_{column} 的输出列,可以在添加订单调用生成的 sql 中使用:

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

回答by penner

When I tried this, rails gave me this error

当我尝试这个时,rails 给了我这个错误

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

请注意,它说 SELECT ... AS count_all

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

所以我更新了@Simon 答案中的查询,看起来像这样,它对我有用

.order('count_all desc')