title: Selecting columns with DISTINCT in PostgreSQL
body: <p>I'm querying bus stops from a database, and I wish to have it only return 1 stop per bus line/direction. This query does just that:</p>
  
  <pre><code>Stop.select("DISTINCT line_id, direction")
  </code></pre>
  
  <p>Except that it won't give me any other attribute than those 2. I tried a couple of other queries to have it return the <code>id</code> in addition to the <code>line_id</code> and <code>direction</code> fields (ideally it would return all columns), with no luck:</p>
  
  <pre><code>Stop.select("DISTINCT line_id, direction, id")
  </code></pre>
  
  <p>and</p>
  
  <pre><code>Stop.select("DISTINCT(line_id || '-' || direction), id")
  </code></pre>
  
  <p>In both cases, the query loses its distinct clause and all rows are returned.</p>
  
  <p>Some awesome dude helped me out and suggested to use a subquery to have it return all the ids:</p>
  
  <pre><code>Stop.find_by_sql("SELECT DISTINCT a1.line_id, a1.direction, (SELECT a2.id from stops a2 where a2.line_id = a1.line_id AND a2.direction = a1.direction ORDER BY a2.id ASC LIMIT 1) as id FROM stops a1
  </code></pre>
  
  <p>I can then extract all the ids and perform a 2nd query to fetch the full attributes for each stop.</p>
  
  <p>Is there a way to have it all inside 1 query AND have it return all the attributes?</p>