What is the equivalent of row_number() over partition in hql I have the following query in hql:
select s.Companyname, p.P
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 results = new ArrayList<>();
Query query = entityManager.createNativeQuery(sQuery);
query.setParameter("n", n);
List
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 ...