row_number()在hql中的分区

时间:2014-04-01 06:05:47

标签: hql window-functions

对于hql中的分区,row_number()的等价物是什么 我在hql中有以下查询:

select s.Companyname, p.Productname, sum(od.Unitprice * od.Quantity - od.Discount) as SalesAmount FROM OrderDetails as od inner join od.Orders as o inner join od.Products as p " +
                                                              "inner join p.Suppliers as s" +
                                                      " where o.Orderdate between '2010/01/01' and '2014/01/01' GROUP BY s.Companyname,p.Productname"

我希望按s.Companyname RowNumber <= n进行分区。

2 个答案:

答案 0 :(得分:3)

据我所知,您无法在HQLJPQL中使用row_number()。我建议在这种情况下使用native SQL查询:

@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);
    }

如果您尝试在HQL中使用OVER(),您几乎肯定会得到一些验证异常,例如java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: OVER near line 1, column 42 ...

答案 1 :(得分:1)

分区的行号如下所示:

row_number() over (partition by s.Companyname)

您不能在row_number子句中使用窗口函数where,因此您必须使用过滤器的值来执行子查询:

select * from (
  -- here is your query
  select 
    ...,
    row_number() over (partition by s.Companyname) as rowNum
  from ...
  where ...
) as res
where rowNum <= n