You want to get the most recent event in the 24 hour cycle.
MAX(CASE WHEN CURRENT_TIME >= EVENTTIME THEN EVENTTIME END)
gives the latest time before CURRENT_TIME
and NULL
if there is none.
You can then use COALESCE
to replace that NULL
with the last event before midnight.
SELECT
SCHEDULEID,
COALESCE(MAX(CASE WHEN CURRENT_TIME >= EVENTTIME THEN EVENTTIME END),
MAX(EVENTTIME)) as EVENTTIME
FROM GET_TODAY_EVENTS
WHERE IS_WORK = 'Y'
GROUP BY SCHEDULEID
If you want to get the details of these events you can JOIN
with the original table.
SELECT mr.SCHEDULEID,mr.EVENTTIME,gte.EVENTTYPEID
FROM
(SELECT
SCHEDULEID,
COALESCE(MAX(CASE WHEN CURRENT_TIME >= EVENTTIME THEN EVENTTIME END),
MAX(EVENTTIME)) as EVENTTIME
FROM GET_TODAY_EVENTS
WHERE IS_WORK = 'Y'
GROUP BY SCHEDULEID) AS mr
JOIN GET_TODAY_EVENTS gte
ON (gte.SCHEDULEID=mr.SCHEDULEID AND gte.EVENTTIME=mr.EVENTTIME)