这个查询
Message.where("message_type = ?", "incoming").group("sender_number").count
会给我一个哈希值。
OrderedHash {"1234"=>21, "2345"=>11, "3456"=>63, "4568"=>100}
现在,我想按每个组的数量进行排序。我如何在查询中做到这一点。
这个查询
Message.where("message_type = ?", "incoming").group("sender_number").count
会给我一个哈希值。
OrderedHash {"1234"=>21, "2345"=>11, "3456"=>63, "4568"=>100}
现在,我想按每个组的数量进行排序。我如何在查询中做到这一点。
Answers:
最简单的方法是在原始查询中添加一个order子句。如果您给count方法指定一个特定的字段,它将生成一个名称为count_ {column}的输出列,该列可在通过添加订单调用生成的sql中使用:
Message.where('message_type = ?','incoming')
.group('sender_number')
.order('count_id asc').count('id')
Message.where(message_type: "incoming").group(:sender_number).order("count(*)").count
Message.where(message_type: "incoming").group(:sender_number).order(:count_all).count
当我尝试这个时,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
注意,它说SELECT ... AS count_all
所以我从@Simon的答案中更新了查询,看起来像这样,它对我有用
.order('count_all desc')
count_all
代替它,count_id
但是在4.2.1中.order("count_id desc")
可以使用。
@test = Price.where('price is not null').group(:price_date).order('count_price asc').count('price')
,它生成SELECT COUNT("prices"."price") AS count_price, price_date AS price_date FROM "prices" WHERE (price is not null) GROUP BY price_date ORDER BY count_price asc