Oracle select most recent date record

后端 未结 4 1781
我在风中等你
我在风中等你 2020-12-16 16:15

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

相关标签:
4条回答
  • 2020-12-16 16:42
    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 讨论(0)
  • 2020-12-16 16:45

    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)
    
    0 讨论(0)
  • 2020-12-16 16:52

    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
    
    0 讨论(0)
  • 2020-12-16 17:04

    i think i'd try with MAX something like this:

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

    then link in your other columns:

    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 讨论(0)
提交回复
热议问题