如何执行单个SQL查询来对activerecord中的分组结果中的列求和?

时间:2016-05-20 12:24:24

标签: ruby-on-rails activerecord

我有两个模型 - ParentParams,其中parent has_many params

目前,我的方法看起来像(不是它在Parent类下):

def total_sum
  params.select(
    'params.*, (
      SUM(mono_volume_annular) + 
      SUM(day_volume_annular) + 
      SUM(night_volume_annular) + 
      SUM(exclusive_volume_annular)
    ) AS summed_volume_annular'
  ).group('params.id').sum(&:summed_volume_annular)
end

如何改进此SQL查询以摆脱.sum(&:summed_volume_annular)方法调用?

如果我在没有将:summed_volume_annular转换为proc的情况下尝试对其进行汇总,我会收到此错误:ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "summed_volume_annular" does not exist

一个有趣的说明 - 如果我将尝试保存此查询的结果

params.select('(
    SUM(mono_volume_annular) + 
    SUM(day_volume_annular) + 
    SUM(night_volume_annular) + 
    SUM(exclusive_volume_annular)
  ) AS summed_volume_annular'
)

我会得到这个对象[#<Parameter:0x00000009f1c7d8 id: nil>]

奇怪summed_volume_annular缺席......

1 个答案:

答案 0 :(得分:1)

我会做这样的事情:

def total_sum
  columns_to_sum = %w(mono_volume_annular day_volume_annular night_volume_annular
                      exclusive_volume_annular)
  sum = columns_to_sum.map{ |col| "COALESCE(#{col}, 0)" }.join(' + ')
  Params.sum(sum)
end