문제

I have a table of Sessions. Each session has "session_start_time" and "session_end_time". While the session is open, the end time is empty. I want to fetch the list of sessions, and order it by the following logic:

  1. If the session is open (no end time), order by the start time.
  2. If the session is closed, order by the end time.

Something like:

 ORDER BY (session_end_time == null) ? session_start_time : session_end_time

I'm using JPA and JPQL for the queries, and using Hibernate for the execution. What would you recommend?

NOTE: I would rather not add CASE to the SELECT, but instead keep it clean so I get a list of sessions without additional unneeded fields.

도움이 되었습니까?

해결책

ORDER BY nvl(session_end_time, session_start_time)

nvl is an Oracle function. I'm sure ther are functions like that for other DBMS

Found this one for hibernate: nvl in HIBERNATE: How to simulate NVL in HQL

ORDER BY: https://forum.hibernate.org/viewtopic.php?f=25&t=997220&start=0

다른 팁

Does

ORDER BY CASE 
    WHEN session_end_time IS NULL THEN session_start_time 
    ELSE session_end_time 
END 

work in your DBMS? That doesn't add a field.

Otherwise you can calculate it inside a nested query, but don't include it in the final SELECT clause:

SELECT field1, field2 FROM (
    SELECT field1, field2, CASE WHEN session_end_time... END AS dummyfield
) Q
ORDER BY Q.dummyfield
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top