如何在JPA中根据分组过滤条件?

How to filter out conditions based on a group by in JPA?

我有一个 table 喜欢

| customer | profile | status | date    | 

| 1        | 1       | DONE   | mmddyy  |

| 1        | 1       | DONE   | mmddyy  |

在这种情况下,我想根据具有最大日期的配置文件 ID 进行分组。配置文件可以重复。我已经排除了 Java 8 个流,因为我这里有很多条件。

我想将以下 SQL 转换为 JPQL:

select customer, profile, status, max(date) 
from tbl 
group by profile, customer,status, date, column-k 
having count(profile)>0 and status='DONE';

有人可以告诉我如何在 JPQL 中编写这个查询,如果它在 SQL 中是正确的吗?如果我在 select 中声明列,则在 group by 中也需要它,并且查询结果不同。

在您的查询中 date columngroup by 中不需要,status='DONE' 应该添加 where clause

select customer, profile, status, max(date) 
from tbl 
where status='DONE'
group by profile, customer,status,  
having count(profile)>0 

我猜您想要最近完成的 customer/profile 组合。

如果是这样,正确的SQL是:

select t.*
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.customer = t.customer and t2.profile = t.profile
               ) and
      t.status = 'DONE';

我不知道如何将其转换为 JPQL,但您不妨从工作 SQL 代码开始。