Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle select most recent date record

Tags:

oracle

I am trying to find the most recent record based on a date field. When I set latest = 1 in the where clause, I get an error. Please help if possible. DATE is a the field I'm sorting by. I have tried both latest = 1 and latest = '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
like image 498
user1440675 Avatar asked Jun 20 '12 21:06

user1440675


People also ask

How do I get the latest timestamp record in SQL?

To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.

How do I find the last updated record in PL SQL?

So, in Oracle database table rows are not in ordered untill and unless you don't have a column by which you will say order by <that_column>. If you wish to get the last updated row, just enable auditing for table and query (timestamp column of dba_audit_trail view) and forget all rest thing.

How do I get the current date in Oracle?

CURRENT_DATE returns the current date in the session time zone, in a value in the Gregorian calendar of datatype DATE. The following statement shows the current date in 'DD-MON-YYYY HH24:MI:SS' format : SQL> ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS'; Session altered.


2 Answers

you can't use aliases from select list inside the WHERE clause (because of the Order of Evaluation of a SELECT statement)

also you cannot use OVER clause inside WHERE clause - "You can specify analytic functions with this clause in the select list or ORDER BY clause." (citation from 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
like image 129
Aprillion Avatar answered Sep 20 '22 23:09

Aprillion


Assuming staff_id + date form a uk, this is another 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)
like image 42
Glenn Avatar answered Sep 19 '22 23:09

Glenn