title: Postgres Rank As Column
body: <p>I have the following query:</p>
  
  <pre><code>SELECT name, rank() OVER (PARTITION BY user_id ORDER BY love_count DESC) AS position FROM items
  </code></pre>
  
  <p>And I'd now like to do a where clause on the rank() function:</p>
  
  <pre><code>SELECT name, rank() OVER (PARTITION BY user_id ORDER BY love_count DESC) AS position FROM items WHERE position = 1
  </code></pre>
  
  <p>That is, I want to query the most loved item for each user. However, this results in:</p>
  
  <p><code>PGError: ERROR:  column "position" does not exist</code></p>
  
  <p>Also, I'm using Rails AREL to do this and would like to enable chaining. This is the Ruby code that creates the query:</p>
  
  <pre><code>Item.select("name, rank() OVER (PARTITION BY user_id ORDER BY love_count DESC) AS position").where("position = 1")
  </code></pre>
  
  <p>Any ideas?</p>