从表中获取最新列,按HQL中的另一列分组

时间:2016-11-20 01:49:26

标签: java postgresql hql

我有一段时间试图弄清楚这个HQL语句。我试图获取组内所有产品订单的最新状态,但似乎无法找出正确的HQL语法以使其正常工作......

示例表:

id | created_at | group_id | purchase_id | status
---|------------|----------|-------------|------------
0  | 10         | 3        | 6           | DELIVERING
1  | 11         | 3        | 6           | DELIVERED
2  | 12         | 3        | 7           | DELIVERING
3  | 13         | 3        | 8           | DELIVERING
4  | 14         | 4        | 13          | DELIVERING
5  | 15         | 4        | 13          | DELIVERED
6  | 16         | 4        | 13          | LOST
7  | 17         | 5        | 17          | DELIVERING

获取每个created_at的最新信息(purchase_id),其中group_id = 3.应该在此表中生成:

id | created_at | group_id | purchase_id | status
---|------------|----------|-------------|------------
1  | 11         | 3        | 6           | DELIVERED
2  | 12         | 3        | 7           | DELIVERING
3  | 13         | 3        | 8           | DELIVERING

在PostgreSQL中运行的查询:

SELECT DISTINCT ON (o.purchase_id) *
FROM orders o
WHERE o.group_id = 3
ORDER BY o.purchase_id, o.created_at DESC

等效的HQL语句是什么?

1 个答案:

答案 0 :(得分:1)

假设每个created_at中的purchase_id值是唯一的,那么下面的HQL应该有效

from Orders
WHERE (purchase_id, created_at) 
      IN  
      (   SELECT purchase_id, max( created_at ) 
          FROM Orders
          GROUP BY purchase_id 
      )

created_at对于给定的purchase_id不唯一时(purchase_id的一个值可能有两个具有相同值created_at的“最新”记录),那么更深的子查询级别是必需的 - 以下HQL将只为每个created_at选择一个记录最高id然后最高purchase_id的记录(这次假设该ID是主键并且是唯一的):

from Orders
WHERE id IN (
   SELECT max( id ) from Orders
   WHERE (purchase_id, created_at) 
         IN  ( 
           SELECT purchase_id, max( created_at ) 
           FROM Orders
           GROUP BY purchase_id 
          )
   GROUP BY purchase_id
 )