"按"分组"计数"的结果?

Moh*_*ain 69 activerecord ruby-on-rails sql-order-by ruby-on-rails-3

这个查询

Message.where("message_type = ?", "incoming").group("sender_number").count
Run Code Online (Sandbox Code Playgroud)

会给我一个哈希值.

OrderedHash {"1234"=>21, "2345"=>11, "3456"=>63, "4568"=>100}
Run Code Online (Sandbox Code Playgroud)

现在我想按每组的数量排序.我该如何在查询中执行此操作.

Sim*_*all 109

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

Message.where('message_type = ?','incoming')
       .group('sender_number')
       .order('count_id asc').count('id')
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你做的这些.与我以前的做法相比,这为我节省了大量时间!最重要的一课:我了解到count方法'将生成一个名为count_ {column}'的输出列!谢谢! (2认同)
  • 从PostgreSQL的Rails 4+开始:`Message.where(message_type:"incoming").group(:sender_number).order("count(*)").count` (2认同)
  • Rails 5 与 PostgreSQL: `Message.where(message_type: "incoming").group(:sender_number).order(:count_all).count` (2认同)

pen*_*ner 16

当我尝试这个时,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
Run Code Online (Sandbox Code Playgroud)

请注意,它表示SELECT ... AS count_all

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

.order('count_all desc')
Run Code Online (Sandbox Code Playgroud)