15

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

4 回答 4

30

您不能在 WHERE 子句中使用选择列表中的别名(因为SELECT 语句的评估顺序

您也不能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
于 2012-06-20T21:26:54.647 回答
5

假设 staff_id + date 来自英国,这是另一种方法:

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)
于 2012-06-20T21:17:02.573 回答
4

我想我会尝试像这样的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
于 2012-06-20T21:10:19.270 回答
3
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
于 2014-01-28T13:24:57.250 回答