mysql - 划分2个查询语句的列表

标签 mysql ruby-on-rails

我有一些查询语句,我想通过基本上执行 top_level_comment_count.fdiv(code_review_assigned_count).round(2)

来取平均值

这是我的 2 个查询语句:

top_level_comment_count = CrucibleComment.group(:user_id).where(parent_comment_id: nil).count
code_review_assigned_count = Reviewer.group(:user_id).count

这两个都返回如下所示的内容:

 40=>5,
 41=>1,
 43=>4,
 44=>10,
 45=>2,
 46=>13,
 48=>7,
 50=>7,
 51=>6,
 52=>5,
 54=>7,
 55=>41,
 56=>2,
 58=>21,
 60=>7,
 61=>8,
 62=>3,
 63=>1,

所以,我想做的是,如果 :user_ids 相同,则取平均值。 我的 def 目前看起来像这样:

  def self.average_top_level_comments
    a = CrucibleComment.group(:user_id).where(parent_comment_id: nil).count
    b = Reviewer.group(:user_id).count
  end

换句话说,我想做这个声明:

return nil unless code_review_assigned_count && top_level_comment_count
top_level_comment_count.fdiv(code_review_assigned_count).round(2)

一组数字。我该怎么做?

For example:
id:40 => 5.0/3.3
id: 41 => 1/2.2
id: 43 => 4 /1.0

最佳答案

我建议使用 inject .

类似于: division_result = top_level_comment_count.inject({}) 做 |result, item| id = item.first 计数 = item.last 结果[id] = count.to_f/code_review_assigned_count[id] 结果 结尾

这将返回一个散列,其中 ID 作为键,除法结果作为值。

关于mysql - 划分2个查询语句的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33788773/

相关文章:

php - 我的 PHP 脚本如何判断服务器是否繁忙?

ruby-on-rails - 未初始化的常量 Gibbon::Request (NameError)

ruby-on-rails - 在设计中获取当前用户 ID

ruby-on-rails - Ruby on Rails : how do you add a class in a link_to helper?

mysql - 创建 MySQL 查询以从现有表创建表

php - 仅在 PHP 中已知的用户记录 MySQL 数据库更改

mysql SET CASE WHEN THEN 与 AND 不是预期结果

mysql - 从 Rails 4.1 的 `:distinct` 中删除弃用的 `Relation#count` 选项

ruby-on-rails - 使用backbone.js 和Ruby on Rails 进行验证

mysql - 向大表添加主键