What is the equivalent of row_number() over partition in hql I have the following query in hql:
select s.Companyname, p.P
Row number by partition looks like this:
row_number() over (partition by s.Companyname)
You can not use window function row_number
in where
clause, so you have to do subquery with filter by its value:
select * from (
-- here is your query
select
...,
row_number() over (partition by s.Companyname) as rowNum
from ...
where ...
) as res
where rowNum <= n
As far as I know you cannot use row_number()
neither in HQL nor in JPQL. I propose to use a native SQL query in this case:
@PersistenceContext
protected EntityManager entityManager;
...
String sQuery = "SELECT q.* FROM (" +
"SELECT s.company_name, " +
"p.product_name, " +
"sum(od.unit_price * od.quantity - od.discount) as SalesAmount, " +
"row_number() OVER (partition by s.company_name) as rn " +
"FROM OrderDetails od " +
"INNER JOIN Orders o ON o.id = od.order_id " +
"INNER JOIN Products p ON p.id = od.product_id " +
"INNER JOIN Suppliers s ON s.id = p.supplier_id " +
"WHERE o.order_date between '2010/01/01' and '2014/01/01') as q " +
"WHERE rn <= :n";
List<ResultDbo> results = new ArrayList<>();
Query query = entityManager.createNativeQuery(sQuery);
query.setParameter("n", n);
List<Object[]> resultSet = query.getResultList();
for (Object[] resultItem : resultSet) {
ResultDbo result = new ResultDbo();
result.setCompanyName((String) resultItem[0]);
result.setProductName((String) resultItem[1]);
result.setSalesAmount((String) resultItem[2]);
results.add(result);
}
If you ever try to use OVER()
in HQL you'll almost certainly get some validation exception like java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: OVER near line 1, column 42 ...