“排序”结果“组”按“数”
问题描述:
Message.where("message_type = ?", "incoming").group("sender_number").count
将返回我的哈希值。
OrderedHash {"1234"=>21, "2345"=>11, "3456"=>63, "4568"=>100}
现在我想按每个组的数量进行排序。我该如何在查询中做到这一点。
答
最简单的方法是只为原始查询添加一个订单子句。如果你给的计数方法的具体领域,它会产生一个名为count_ {列},它可以通过添加顺序调用生成的SQL中使用的输出列:当我尝试这样做
Message.where('message_type = ?','incoming')
.group('sender_number')
.order('count_id asc').count('id')
答
,轨给了我这个错误
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
所以我更新从@西门的答案查询到这个样子,它为我的作品
.order('count_all desc')
不能为我工作.. –
您使用哪个数据库引擎?哪个版本的rails,以及生成的sql是什么?我刚刚有一个测试用例(不同的模型)在轨道3.0.7上正常工作......例如(价格不为空)。group(:price_date).order('count_price asc')。count('price')',产生'SELECT COUNT(“价格”。“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' –
非常感谢您的支持。与我以前的工作方式相比,这节省了我很多的时间!最重要的一课:我了解到count方法会生成一个名为count_ {column}的输出列!谢谢! – Yavin4