命名查询 SELECT 行,MAX(列名),DISTINCT 由另一列

Named Query to SELECT rows with MAX(column name), DISTINCT by another column

我有一个类似于 this question 中描述的案例,我编写了一个相同的查询,但当我尝试将其编写为 jpql 命名查询时,出现错误。

我的查询:

@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"
            )

错误:

Error in named query: findRankingsBetween: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 79

如何在jpql中正确编写查询?

this answer 中所述,JPQL 中的子查询只能出现在 select 和 where 子句中。 Hibernate doc.

JPQL 中的等效查询是:

"SELECT rt FROM Rankingtable rt " +
"WHERE rt.lastupdate = (SELECT MAX(r2.lastupdate) " +
                       "FROM Rankingtable r2 " +
                       "WHERE r2.teamid = rt.teamid) " +
"AND rt.lastupdate BETWEEN :from AND :to"