【问题标题】:"Order by" result of "group by" count?“分组依据”计数的“排序依据”结果?
【发布时间】:2023-03-13 08:50:02
【问题描述】:

这个查询

Message.where("message_type = ?", "incoming").group("sender_number").count

会返回一个哈希值。

OrderedHash {"1234"=>21, "2345"=>11, "3456"=>63, "4568"=>100}

现在我想按每个组的数量排序。我怎样才能在查询中做到这一点。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord sql-order-by


    【解决方案1】:

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

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

    【讨论】:

    • 您使用的是哪个数据库引擎?哪个版本的rails,生成的sql是什么?我刚刚有一个测试用例(不同型号)在 rails 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
    • 非常感谢您。与以前的查询相比,这为我节省了很多时间!最重要的一课:我了解到 count 方法会生成一个名为 count_{column} 的输出列!谢谢!
    • 我不敢相信这只有 35 个(现在是 36 个)赞成票。太有用了!
    • 从带有 PostgreSQL 的 Rails 4+ 开始:Message.where(message_type: "incoming").group(:sender_number).order("count(*)").count
    • 带有 PostgreSQL 的 Rails 5:Message.where(message_type: "incoming").group(:sender_number).order(:count_all).count
    【解决方案2】:

    当我尝试这个时,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") 有效。
    • 为我工作。也许你错过了 .count('id')?
    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多