Ruby ActiveRecord按自定义字段查询总和

时间:2016-09-25 19:52:50

标签: sql ruby-on-rails postgresql activerecord

我有一个名为Answer的模型,其中包含has_one QuestionQuestiondimension_id, possible_answers 我有以下查询

Answer.joins(:question).select(:dimension_id,"(CAST(answers.answer AS FLOAT) / (length(possible_answers))) AS satisfaction").where(:created_at => date_from..date_to)

我想按维度_id对结果进行分组,并按满意度求和,以便获得每个维度的满意度,但如果我.group(:dimension_id).sum(:satisfaction)我收到错误PG::UndefinedColumn: ERROR: column "satisfaction" does not exist

我应该如何总结满意度以获得理想的结果? 谢谢

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

Answer.where(:created_at => date_from..date_to).joins(:question).select("answers.dimension_id, sum(CAST(answers.answer AS FLOAT) / (length(possible_answers))) AS satisfaction").group('answers.dimension_id')

我认为您的dimension_id位于answers,如果没有将answers.dimension_id更改为questions.dimension_id