Oracle选择最新的日期记录

时间:2012-06-20 21:07:00

标签: oracle

我正在尝试根据日期字段查找最新记录。当我在where子句中设置latest = 1时,我收到错误。请尽可能帮助。 DATE是我正在排序的字段。我已经尝试了最新的= 1和最新的='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

4 个答案:

答案 0 :(得分:16)

你不能在WHERE子句中使用select列表中的别名(因为SELECT语句的 Order of Evaluation

您也不能在WHERE子句中使用OVER子句 - “您可以在选择列表或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

答案 1 :(得分:2)

假设staff_id +日期形成英国,这是另一种方法:

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)

答案 2 :(得分:1)

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

答案 3 :(得分:0)

我想我会尝试使用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