title: Doctrine COUNT in subquery with HAVING
body: <p>I am trying to get a list of user rankings for the leaderboard. I have three tables:</p>
  
  <ul>
  <li>users (id, username)</li>
  <li>circuits (id, name)</li>
  <li>user_circuits (id, user, circuit, record)</li>
  </ul>
  
  <p>The records are calculated correctly but I always get the <strong>total number of users</strong> instead of the ranking. This is my query:</p>
  
  <pre><code>$query = $em-&gt;createQuery('
      SELECT
          u.id AS id,
          u.username AS username,
          COALESCE(MAX(c.record), 0) AS record,
          (
              SELECT
                  COUNT(DISTINCT u2.id)
              FROM ApplicationSonataUserBundle:User u2
              LEFT JOIN u2.circuits c2
              HAVING COALESCE(MAX(c2.record), 0) &gt; record
          ) AS ranking
      FROM ApplicationSonataUserBundle:User u
      LEFT JOIN u.circuits c
      GROUP BY id, username
      ORDER BY record DESC
  ');
  
  $leaderboard = $query
      -&gt;setMaxResults($max)
      -&gt;getArrayResult()
  ;
  </code></pre>
  
  <p>This is the result:</p>
  
  <pre><code>UserRepository.php on line 88:
  array:20 [
    0 =&gt; array:4 [
      "id" =&gt; 427
      "username" =&gt; "ninety-nine"
      "record" =&gt; "99"
      "ranking" =&gt; "102"
    ]
    1 =&gt; array:4 [
      "id" =&gt; 426
      "username" =&gt; "ninety-eight"
      "record" =&gt; "98"
      "ranking" =&gt; "102"
    ]
    2 =&gt; array:4 [
      "id" =&gt; 425
      "username" =&gt; "ninety-seven"
      "record" =&gt; "97"
      "ranking" =&gt; "102"
    ]
    3 =&gt; array:4 [
      "id" =&gt; 424
      "username" =&gt; "ninety-six"
      "record" =&gt; "96"
      "ranking" =&gt; "102"
    ]
    4 =&gt; array:4 [
      "id" =&gt; 423
      "username" =&gt; "ninety-five"
      "record" =&gt; "95"
      "ranking" =&gt; "102"
    ]
  ]
  </code></pre>