简体   繁体   中英

JPQL greatest-n-per-group query

Is there a way to write this query using JPQL:

select *
from "tbCita" c inner join "tbAccionCita" ac1
on c."citaId" = ac1."citaId"
left outer join "tbAccionCita" ac2 on ( c."citaId" = ac2."citaId" and
    (ac1."fechaAccionCita" < ac2."fechaAccionCita" 
     or ac1."fechaAccionCita" = ac1."fechaAccionCita" 
     and ac1."accionCitaId" < ac2."accionCitaId")
 )
 inner join "tbUsuarioCita" uc 
    on c."citaId" = uc."citaId"
  inner join "tbUser" u 
    on uc."userId" = u."userId"
 where 
    ac2."accionCitaId" is null
    and u."userId" = 1

fechaAccionCita is a date :)

I'm trying to get the latest state (one appointment has multiple states) for all the appointments (tbCita) with userId = 1.

The query is working as expected, but in JPQL it gives me the following error:

with-clause referenced two different from-clause elements

Here the query:

SELECT c "
        + "FROM Cita c "
        + "INNER JOIN c.usuarioCita u "
        + "INNER JOIN FETCH c.accionCita a "
        + "LEFT OUTER JOIN c.accionCita a2 on (a.fechaAccionCita < a2.fechaAccionCita or "
        + "a.fechaAccionCita = a2.fechaAccionCita and a.accionCitaId < a2.accionCitaId) "

Does the following work? Also, are you sure the logic in the OR statement working as expected? It seems you might need an additional set of parentheses.

select c
from tbCita c, tbAccionCita ac1, tbUsuarioCita uc, tbUser u 
left join tbAccionCita ac2 on (
    c.citaId = ac2.citaId 
    and (ac1.fechaAccionCita < ac2.fechaAccionCita 
        or ac1.fechaAccionCita = ac1.fechaAccionCita 
        and ac1.accionCitaId < ac2.accionCitaId))
where c.citaId = ac1.citaId
    and c.citaId = uc.citaId
    and uc.userId = u.userId
    and ac2.accionCitaId is null
    and u.userId = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM