【问题标题】:Rails & Active Record: Get the average value of a column after groupingRails & Active Record:分组后获取列的平均值
【发布时间】:2016-09-15 05:26:18
【问题描述】:

我有一个表 user_keywords :belongs_to :keywords。 user_keywords 有一列keyword_id、user_id 和relevant_score (float)。

关键字表有一个“名称”列。

  1. 我想按他们的keyword_id 对所有user_keywords 进行分组。
  2. 我想取每个组的相关性得分的平均值
  3. 我想按最高相关性分数对组进行排序
  4. 我想从组中返回关键字的名称,按最高相关性得分排序。

查询这个最有效的方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    试试这个:

    Keyword.joins(:user_keywords)
    .select('keywords.name, avg(user_keywords.relevance_score) as score')
    .group('keywords.name')
    .order('score DESC')
    .map(&:name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      相关资源
      最近更新 更多