如何将find_by_sql(SUM(字段))的结果存储到变量中?

时间:2017-05-23 16:25:54

标签: sql ruby-on-rails

我有一个我想要捕获的SQL查询。这是查询:

sl = SlocMetric.find_by_sql("select sum(code_added), 
     sum(comments_added), sum(blanks_added), sum(code_removed), 
     sum(comments_removed), sum(blanks_removed) from sloc_metrics
       inner join diffs on diffs.id = sloc_metrics.diff_id 
       inner join commits on commits.id = diffs.commit_id 
    where commits.id = '499848202'")

这个查询在实际SQL中的输出会给我一个包含四个和值的表,如下所示:

sum| sum| sum| sum|
1     23   43   34

有没有办法可以捕获这些值而无需使用ActiveRecord。我知道有一个.sum方法但是为了使用它,我必须在ActiveRecord中真正修改查询和/或使用我真的不想使用的Arel。帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用ActiveRecord::Base.connection.select_rows(),它会返回一个数组数组,其中每一行都由一个具有SELECT值的数组表示。例如,在您的情况下,您将执行:

sl = ActiveRecord::Base.connection.select_rows("select sum(code_added), 
     sum(comments_added), sum(blanks_added), sum(code_removed), 
     sum(comments_removed), sum(blanks_removed) from sloc_metrics
       inner join diffs on diffs.id = sloc_metrics.diff_id 
       inner join commits on commits.id = diffs.commit_id 
    where commits.id = '499848202'")

输出将是:

#=> [[1, 23, 43, 34]]

现在您可以使用s1[0]访问值,因为您的查询只输出一行:

sl[0].inspect
#=> "[1, 23, 43, 34]"

答案 1 :(得分:0)

您可以为每个sum命名,即:

sl = SlocMetric.find_by_sql("select sum(code_added) as sum_1, 
     sum(comments_added) as sum_2, sum(blanks_added) as sum_3, sum(code_removed) as sum_4, 
     sum(comments_removed) as sum_5, sum(blanks_removed) as sum_6 from sloc_metrics
       inner join diffs on diffs.id = sloc_metrics.diff_id 
       inner join commits on commits.id = diffs.commit_id 
    where commits.id = '499848202'")

结果是SlocMetric个对象的数组,然后您应该能够在每个元素中访问它,例如:

sl[0].sum_1