I have following JPA entity (getters, setter and non relevant fields omitted):
@Entity
@Table(name = "transaction")
public class Transaction {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "start_date", nullable = false)
private Date startDate;
}
My goal is to implement queries using JPQL or criteria API, which will return average amount of transactions per day and maximal amount of transactions per day.
Native SQL queries (MySQL database) giving the desired result look like this:
select max(cnt) from (
select date(start_date) start_date, count(t.id) cnt
from transaction t
group by date(t.start_date)
) t;
select avg(cnt) from (
select date(start_date) start_date, count(t.id) cnt
from transaction t
group by date(t.start_date)
) t;
Unfortunately usage of native SQL queries is discouraged and JPQL does not allow using subqueries in where clause.
Thank you in advance.
Addition:
I started with following Spring Data query:
@Query("select max(cnt) from ("
+ "select date(t.startDate) startDate, count(t.id) cnt "
+ "from Transaction t "
+ "group by date(t.startDate))")
But it obviously didn't work:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 22 [select max(cnt) from (select date(t.startDate) startDate, count(t.id) cnt from Transaction t group by date(startDate))]
I can imagine, that using sorting and limiting the output it's possible to manage search for max, but that will not help for avg.