“排序依据”是“分组依据”的结果?


Answers:


120

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

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

1
您正在使用哪个数据库引擎?哪个版本的rails,生成的sql是什么?我刚刚有一个测试用例(不同的模型)可以在3.0.7上的轨道上正常工作,例如@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
Simon Elliston Ball

2
非常感谢你做的这些。与以前相比,这节省了我很多时间!最重要的一课:我了解到count方法“将生成一个名称为count_ {column}的输出列”!谢谢!
northdig 2014年

我不敢相信这只有35个(现在36个)投票。太有用了!
jeffdill2

3
从PostgreSQL到Rails 4+:Message.where(message_type: "incoming").group(:sender_number).order("count(*)").count
David Aldridge

2
Rails 5与PostgreSQL:Message.where(message_type: "incoming").group(:sender_number).order(:count_all).count
Snow Fox,

18

当我尝试这个时,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')

不确定使用哪个AR版本count_all代替它,count_id但是在4.2.1中.order("count_id desc")可以使用。
sameers 2015年

为我工作。也许您错过了.count('id')?
mahemoff 2015年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.