title: Ruby on Rails: Sum table column row values based on other column data
body: <p>I have a table with columns 'id', 'resource_id', 'read_time', 'value' where 'value' is a float</p>
  
  <p>What I am trying to accomplish is to return a list of records such that the 'value' of each record is the sum of all the records at a specific 'read_time' but having differing 'resource_id' values.</p>
  
  <p>I am wondering if there is a clever way (ie not looping through all the entries) to accomplish this. Currently I am implementing something along these lines:</p>
  
  <pre><code>@aggregate_meters = []
  @res_one_meters = Meter.find(:all, :conditions =&gt; ["resource_id = ?", 1])
  
  @res_one_meters.each do |meter|
    read_time = meter.read_time
    value = meter.value
    if res_two_meter = Meter.find(:first, :conditions =&gt; ["resource_id = ? AND read_time = ?", 2, read_time ])
      value = value + res_two_meter.value
    end
    aggregate_meter = Meter.new(:read_time =&gt; read_time, :value =&gt; value, :resource_id =&gt; 3)
    @aggregate_meters.push(aggregate_meter)
  end
  </code></pre>
  
  <p>Thank you.</p>