Oracle selects the most recent date entry

I am trying to find the most recent entry based on a date field. When I set last = 1 in the where clause, I get an error. Please help if possible. DATE is the field I'm sorting. I tried both last = 1 and last = '1'

SELECT 
STAFF_ID,
SITE_ID,
PAY_LEVEL,
ROW_NUMBER() OVER (PARTITION BY STAFF_ID ORDER BY DATE DESC) latest

 FROM OWNER.TABLE
WHERE   END_ENROLLMENT_DATE is null 
AND latest = 1
+5
source share
4 answers

you cannot use aliases from the select list inside the WHERE clause (due to the Order of Evaluation of the SELECT statement )

OVER WHERE - " ORDER BY". ( docs.oracle.com)

select *
from (select
  staff_id, site_id, pay_level, date, 
  max(date) over (partition by staff_id) max_date
  from owner.table
  where end_enrollment_date is null
)
where date = max_date
+11

, MAX - :

SELECT staff_id, max( date ) from owner.table group by staff_id

:

select staff_id, site_id, pay_level, latest
from owner.table, 
(   SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date
0

Assuming staff_id + date form uk, this is a different method:

SELECT STAFF_ID, SITE_ID, PAY_LEVEL
  FROM TABLE t
  WHERE END_ENROLLMENT_DATE is null
    AND DATE = (SELECT MAX(DATE)
                  FROM TABLE
                  WHERE staff_id = t.staff_id
                    AND DATE <= SYSDATE)
0
source
select *
from (select
  staff_id, site_id, pay_level, date, 
  rank() over (partition by staff_id order by date desc) r
  from owner.table
  where end_enrollment_date is null
)
where r = 1
0
source

All Articles