title: Using DISTINCT based on a single column in GROUP BY
body: <p>This question tends to come up a lot, but I haven't quite found an answer that makes sense to me or is applicable.</p>
  
  <p>Consider this table:</p>
  
  <pre><code>order_id   user_id   order_date
  1           1        2012-01-01
  1           1        2012-01-15
  2           2        2012-01-15
  2           2        2012-01-20
  2           2        2012-01-25
  3           2        2012-01-15
  3           2        2012-01-16
  4           2        2012-01-15
  4           2        2012-01-16
  </code></pre>
  
  <p>I want to retrieve (order_id, user_id) where the user_id is distinct, based on some conditions on the order_date.</p>
  
  <p>So far I have this query:</p>
  
  <pre><code>SELECT user_id, order_id, MAX(order_date) FROM orders
  GROUP BY order_id
  HAVING
  MAX(order_date) &lt; '2012-01-20'
  </code></pre>
  
  <p>Which returns</p>
  
  <pre><code>user_id   order_id   MAX(order_date)
  1          1         2012-01-15
  2          3         2012-01-16
  2          4         2012-01-16
  </code></pre>
  
  <p>However, I want this result set to also group on on user_id, based on the maximum order_id. I want:</p>
  
  <pre><code>user_id   order_id   MAX(order_date)
  1          1         2012-01-15
  2          4         2012-01-16
  </code></pre>
  
  <p>How can I do a GROUP BY based on order_id, and then subsequently group (or possibly distinct, if I drop the requirement of having the MAX order_id) on user_id?</p>