title: Named Query to SELECT rows with MAX(column name), DISTINCT by another column
body: <p>I have a case similar to the one described in <a href="https://stackoverflow.com/questions/612231/how-can-i-select-rows-with-maxcolumn-value-distinct-by-another-column-in-sql">this question</a>, I wrote an identical query which works, but when I try to write it as a jpql named query, I'm getting an error.</p>
  
  <p>My query:</p>
  
  <pre><code>@NamedQuery(
              name = "findRankingsBetween",
              query = "SELECT rt FROM Rankingtable rt " +
                          "INNER JOIN " +
                              "(SELECT teamId, MAX(lastupdate) as MaxDateTime " +
                              "FROM Rankingtable " +
                              "GROUP BY teamId) grouped " +
                          "ON rt.teamId = grouped.teamId " +
                          "AND rt.lastupdate = grouped.MaxDateTime " +
                      "WHERE rt.lastupdate BETWEEN :from AND :to"
              )
  </code></pre>
  
  <p>Error:</p>
  
  <pre><code>Error in named query: findRankingsBetween: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 79
  </code></pre>
  
  <p>How to write the query properly in jpql?</p>