title: Re-write a query to avoid PG::GroupingError: ERROR: in the GROUP BY clause or be used in an aggregate function
body: <p>I tried many alternatives before posting this question.
  I have a query on a table A with columns: id, num, user_id.
  id is PK, user_id can be duplicate. 
  I need to have all the rows such that only unique user_id has chosen to have highest num value. For this, I came up with aSQL below, which will work in Oracle database. I am on ruby on rails platform with Postgres Database.</p>
  
  <pre><code>select stats.* from stats as A 
  where A.num &gt; (
        select B.num
        from stats as B
        where A.user_id == B.user_id 
        group by B.user_id  
        having B.num&gt; min(B.num) ) 
  </code></pre>
  
  <p>I tried writing this query via active record method but still ran into </p>
  
  <blockquote>
    <p>PG::GroupingError: ERROR:  column "b.num" must appear in the GROUP BY
    clause or be used in an aggregate function</p>
  </blockquote>
  
  <pre><code>Stat.where("stats.num &gt; ( select B.nums from stats as B  where stats.user_id = B.user_id group by B.user_id having B.num &lt; max(B.num) )")
  </code></pre>
  
  <p>Can someone tell me alternative way of writing this query</p>