title: Combining Active Record group, join, maximum & minimum
body: <p>I'm trying to get to grips with the Active Record query interface.  I have two models:</p>
  
  <pre><code>class Movie &lt; ActiveRecord::Base
    has_many :datapoints
    attr_accessible :genre
  end
  
  class Datapoint &lt; ActiveRecord::Base  
    belongs_to :movie  
    attr_accessible :cumulative_downloads, :timestamp
  end
  </code></pre>
  
  <p>I want to find the incremental downloads per genre for a given time period.  </p>
  
  <p>So far I've managed to get the maximum and minimum downloads per movie within a time period, like so:</p>
  
  <pre><code>maximums = Datapoint.joins(:movie)
      .where(["datapoints.timestamp &gt; ?", Date.today - @timespan])
      .group('datatpoints.movie_id')
      .maximum(:cumulative_downloads)
  </code></pre>
  
  <p>This then allows me to calculate the incremental per movie, before aggregating this into the incremental per genre.</p>
  
  <p>Clearly this is a bit ham-fisted, and I'm sure it would be possible to do this in one step (and using hash conditions).  I just can't get my head around how.  Can you help?</p>
  
  <p>Much appreciated!</p>
  
  <p>Derek.</p>