Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a case similar to the one described in this question, I wrote an identical query which works, but when I try to write it as a jpql named query, I'm getting an error.

My query:

@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:

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

How to write the query properly in jpql?

like image 669
Bartek Maraszek Avatar asked Jan 06 '15 08:01

Bartek Maraszek


People also ask

Can we use MAX function in where clause?

The MAX() function is used with the WHERE clause to gain further insights from our data. In SQL, the MAX() function computes the highest or maximum value of numeric values in a column.

How do I get the maximum value from multiple columns in SQL?

If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...) Given two or more arguments, it returns the largest (maximum-valued) argument.

How do I select a maximum value in a column in SQL?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.

How do I find the maximum value of a row in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).


1 Answers

As noted in this answer, a subquery in JPQL can only occur in select and where clauses. Hibernate doc.

An equivalent query in JPQL is:

"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"
like image 179
Bartek Maraszek Avatar answered Oct 21 '22 00:10

Bartek Maraszek