【问题标题】:Calculate grouped average using activerecord/pgsql使用 activerecord/pgsql 计算分组平均值
【发布时间】:2016-05-29 15:20:43
【问题描述】:

我有一个简单的comments 表:

id    post_id
=======================
1     'a11'
2     'a11'
3     'b22'
4     'b22'
5     'b22'

我正在计算每个帖子的平均 cmets:

comment_counts = Comment.group(:post_id).count.values
avg = comment_counts.sum / comment_counts.size.to_f
# => 2.5

我更愿意让 DB 处理计算。如何仅使用 activerecord/sql 来实现这一点?

【问题讨论】:

    标签: sql ruby-on-rails postgresql activerecord


    【解决方案1】:

    我想不出一种非常 ActiveRecord-ish 的方法,但可以提供以下内容:

    Comment(:post_id).select("avg(count(*)) over () avg").take.avg
    

    ... 返回 BigDecimal,或者可能更有效:

    ActiveRecord::Base.connection.execute("select avg(c_star) from (select count(*) c_star from comments group by post_id) t").first["avg"].to_d
    

    不过,我突然想到,这并没有考虑到没有收到评论的帖子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多