另一种选择是使用窗口函数LEAD
(或LAG
取决于您对结果的排序方式)。在此示例中,我们标记状态随日期变化的行,对结果进行排序并排除除第一个以外的行:
with test_data as (
select 1 status, date '2012-07-26' status_date from dual union all
select 1 status, date '2012-07-24' status_date from dual union all
select 1 status, date '2012-07-22' status_date from dual union all
select 2 status, date '2012-07-21' status_date from dual union all
select 2 status, date '2012-07-19' status_date from dual union all
select 1 status, date '2012-07-16' status_date from dual union all
select 0 status, date '2012-07-14' status_date from dual)
select status, as_of
from (
select status
, case when status != lead(status) over (order by status_date desc) then status_date else null end as_of
from test_data
order by as_of desc nulls last
)
where rownum = 1;
附录:LEAD
and函数接受
另外LAG
两个参数:offset
and default
。offset
默认为 1,默认default
为 null。默认值允许您确定当您位于结果集的开头或结尾时要考虑的值。在您的状态从未改变的情况下,需要一个默认值。在此示例中,我提供了 -1 作为默认状态,因为我假设状态值不是您预期的集合的一部分:
with test_data as (
select 1 status, date '2012-07-25' status_date from dual union all
select 1 status, date '2012-07-24' status_date from dual union all
select 1 status, date '2012-07-20' status_date from dual)
select status, as_of
from (
select status
, case when status != lead(status,1,-1) over (order by status_date desc) then status_date else null end as_of
from test_data
order by as_of desc nulls last
)
where rownum = 1;
您可以使用 case 条件(等于/不等于)、前导函数中的 order by 子句以及满足您需求的所需默认值。