title: Selecting rows ordered by some column and distinct on another
body: <p>Related to - <a href="https://stackoverflow.com/questions/9795660/postgresql-distinct-on-without-ordering">PostgreSQL DISTINCT ON with different ORDER BY</a></p>
  
  <p>I have table purchases (product_id, purchased_at, address_id)</p>
  
  <p>Sample data:</p>
  
  <pre><code>| id | product_id |   purchased_at    | address_id |
  | 1  |     2      | 20 Mar 2012 21:01 |     1      |
  | 2  |     2      | 20 Mar 2012 21:33 |     1      |
  | 3  |     2      | 20 Mar 2012 21:39 |     2      |
  | 4  |     2      | 20 Mar 2012 21:48 |     2      |
  </code></pre>
  
  <p>The result I expect is the most recent purchased product (full row) for each address_id and that result must be sorted in descendant order by the purchased_at field:</p>
  
  <pre><code>| id | product_id |   purchased_at    | address_id |
  | 4  |     2      | 20 Mar 2012 21:48 |     2      |
  | 2  |     2      | 20 Mar 2012 21:33 |     1      |
  </code></pre>
  
  <p>Using query:</p>
  
  <pre><code>SELECT DISTINCT ON (address_id) purchases.address_id, purchases.*
  FROM "purchases"
  WHERE "purchases"."product_id" = 2
  ORDER BY purchases.address_id ASC, purchases.purchased_at DESC
  </code></pre>
  
  <p>I'm getting:</p>
  
  <pre><code>| id | product_id |   purchased_at    | address_id |
  | 2  |     2      | 20 Mar 2012 21:33 |     1      |
  | 4  |     2      | 20 Mar 2012 21:48 |     2      |
  </code></pre>
  
  <p>So the rows is same, but order is wrong. Any way to fix it?</p>