title: postgres group by aggregate function
body: <p>I have a messages table which looks like this:</p>
  
  <pre><code>+------------+-------------+----------+
  | sender_id  |  created_at | message  |
  +------------+-------------+----------+
  |      1     | 2010-06-14  | the msg  |
  |      1     | 2010-06-15  | the msg  |
  |      2     | 2010-06-16  | the msg  |
  |      3     | 2010-06-14  | the msg  |
  +------------+-------------+----------|
  </code></pre>
  
  <p>I want to select the single most recent message for each sender. </p>
  
  <p>This seems like a GROUP BY sender_id and ORDER BY created_at but I'm having trouble getting the most recent message selected.</p>
  
  <p>I'm using postgres so need an aggregate function on the created_at field in the SELECT statement if I want to order by that field so I was looking at doing something like this as an initial test</p>
  
  <pre><code>SELECT messages.sender_id, MAX(messages.created_at) as the_date 
  FROM messages 
  GROUP BY sender_id 
  ORDER BY the_date DESC 
  LIMIT 10;
  </code></pre>
  
  <p>This seems to work but when I want to select 'message' as well I have no idea what aggregate function to use on it. I basically just want the message that corresponds to the MAX created_at. </p>
  
  <p>Is there some way of getting at this or am I approaching it the wrong way?</p>