每组最后记录

Last record in each group

我使用的是oracle 11.2,我尝试获取每个组中的最后一条记录。

在我的 ce table 我有 id, date, name 字段。

select ce1.*
from ce ce1
inner join 
  (select account_id, max(date) as max_date from ce group by account_id ) as group_id
   on ce1.account_id=group_id.account_id
  and ce1.date=group_id.max_date
where ce1.account_id in (....)

效果不错

我尝试在 jpql 中转换它但没有成功,我的 jpa 实现是休眠的

select ce1
    from ce ce1
    inner join 
      (select accountId as accountId, max(date) maxDate from ce group by accountId ) as group_id
       on ce1.accountId=group_id.accountId
      and ce1.date=group_id.maxDate
    where ce1.accountId in (....)

Jpa 似乎不喜欢 innerjoin 和 max

意外的令牌( 意外标记最大值

假设实体 Ce:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Ce> cq = cb.createQuery(Ce.class);

Root<Ce> rootCe = cq.from(Ce.class);

Subquery<Date> sqMaxDate = cq.subquery(Date.class);
Root<Ce> sqRootCe = sqMaxDate.from(Ce.class);
sqMaxDate.where(cb.equal(rootCe.get(Ce_.accountId),sqRootCe.get(Ce_.accountId)));
sqMaxDate.select(cb.max(sqRootCe.get(Ce_.date)));

cq.where(cb.and(cb.equal(rootCe.get(Ce_.date),sqMaxDate.getSelection()),
                 rootCe.get(Ce_.accountId).in([...])));

本次查询结果:

Select * from CE ce1
Where ce1.account_id in ([...])
    and ce1.date = (
        select max(date) from CE ce2
        where ce1.account_id = ce2.account_id
    );

没有实体我相信这个解决方案是有效的。我们获取每个帐户 ID 的最大日期并将其设置为主查询的条件