JPA - Postgres - 如何使用Distinct和Group By从表中获取结果

时间:2016-08-17 14:13:25

标签: postgresql jpa group-by distinct

假设我有一个用户表/实体对象,如下所示:

user
-------
user_id (long)
person_name (String)
employee_type (String)
age (integer)

给定user_id列表,我想编写一个JPQL查询,该查询将返回每个不同“employee_type”的OLDEST用户。有可能这样做吗?

2 个答案:

答案 0 :(得分:1)

您可以使用EXISTS子查询:

SELECT * 
FROM user u WHERE EXISTS 
(
    SELECT 'found'
    FROM user t
    WHERE t.employee_type = u.employee_type
    GROUP BY t.employee_type
    HAVING MAX(t.age) = u.age
) 

答案 1 :(得分:0)

试试

Select u from user u
 where u.userId in (:userId)
   and u.age = (
      select max(u1.age) from user u1 
                         where u1.userId in (:userId)
                           and u1.userType = u.userType 
)