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}
現在我想按每個組的數量進行排序。我該如何在查詢中做到這一點。
最簡單的方法是隻爲原始查詢添加一個訂單子句。如果你給的計數方法的具體領域,它會產生一個名爲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