【问题标题】:How to filter out conditions based on a group by in JPA?如何在 JPA 中根据 group by 过滤条件?
【发布时间】:2019-11-28 11:44:33
【问题描述】:

我有一张这样的桌子

| 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';

如果在 SQL 中正确,谁能告诉我如何在 JPQL 中编写此查询?如果我在select 中声明列,则分组也需要它,并且查询结果不同。

【问题讨论】:

    标签: sql jpa jpql


    【解决方案1】:

    我猜你想要最近完成的客户/资料组合。

    如果是,正确的 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 代码开始。

    【讨论】:

    • 谢谢你的作品!我假设这不能以简单的方式使用 group by 和 having 子句来完成。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多