title: How to aggregate alias column in activerecord?
body: <p>Suppose to have the following table:</p>
  
  <pre class="lang-ruby prettyprint-override"><code> Product(id:integer, category:string, cost:float)
  </code></pre>
  
  <p>And you want to perform this query with <code>activerecord</code>:</p>
  
  <pre class="lang-ruby prettyprint-override"><code>Product.select("cost + 1000 AS incremented_cost").group(:category).sum('incremented_cost')
  
  ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "incremented_cost" does not exist
  </code></pre>
  
  <p>The example is quite simplified, however it well represents the problem: how can I assign an alias to a modified field and the use it in an aggregate function?</p>
  
  <p>My goal is to return an Activerecord_Relation where it is possible to compute aggregations on a alias field, possibly on a group. The problem is that "grouping" is conditional and I would like to keep the data pipeline.</p>
  
  <p><code>select</code> method does not work because it does not change the fields names of a relation. If you use "AS" it is possible to access the alias (see link). However it does not work in aggregate functions.
  See: <a href="http://apidock.com/rails/v4.1.8/ActiveRecord/QueryMethods/select" rel="nofollow">http://apidock.com/rails/v4.1.8/ActiveRecord/QueryMethods/select</a></p>
  
  <p>Using <code>#inject</code> it is not a good solution for me, I don't want to deal with arrays.</p>
  
  <p>For instance this code gives the right result, but it's not a good solution for me:</p>
  
  <pre><code>Product.select("cost + 1000 AS incremented_cost").inject(0) do |acc, record|
     acc + record.incremented_cost
  end    
  </code></pre>