row_number() over partition in hql

后端 未结 2 513
无人及你
无人及你 2021-02-09 10:40

What is the equivalent of row_number() over partition in hql I have the following query in hql:

select s.Companyname, p.P         


        
相关标签:
2条回答
  • 2021-02-09 11:22

    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
    
    0 讨论(0)
  • 2021-02-09 11:38

    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 ...

    0 讨论(0)
提交回复
热议问题