title: Aggregate function returning first row data for column not in the group by
body: <p>I have a table relationship that looks like the following:</p>
  
  <pre><code>barn
  ------
  PK barn_id
  &lt;other columns&gt;
  
  stable
  ---------
  PK stable_id
  FK barn_id
  stable_number
  stable_contents
  timestamp
  </code></pre>
  
  <p>So whenever the contents of a stable change I just put in a new row with the corresponding barn_id and stable_number with new stable_contents and a current timestamp.</p>
  
  <p>The tables are designed this way so I can look at a certain stable and see its entire history.</p>
  
  <p>I am trying to write a query that will find me the current state of all the stables in all the barns, so I try this:</p>
  
  <pre><code>SELECT barn_id, stable_number, max(timestamp), stable_contents
  FROM stable
  GROUP BY barn_id, stable_number
  </code></pre>
  
  <p>In my test data I have some rows like this for barn 1, stable 7</p>
  
  <pre><code>1 | 7 | 2009-12-09 10:00:00 | empty
  1 | 7 | 2009-12-10 10:30:00 | show horse
  </code></pre>
  
  <p>If I run the <code>SELECT</code> query above, I get the following row returned for barn 1, stable 7:</p>
  
  <pre><code>1 | 7 | 2009-12-10 10:30:00 | empty
  </code></pre>
  
  <p>it gets the right maximum timestamp, just the wrong stable_contents.</p>
  
  <p>Any ideas?</p>