我根据您的方案做了一些测试,如下所示
create table table1 (id integer, nm integer, stdate date, endate date);
插入了一些测试数据
Insert into TABLE1(ID, NM, STDATE, ENDATE)
Values (1, 2, TO_DATE('04/09/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('06/17/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into TABLE1(ID, NM, STDATE, ENDATE)
Values(1, 1, TO_DATE('03/25/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('06/14/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into TABLE1(ID, NM, STDATE, ENDATE)
Values(2, 3, TO_DATE('03/05/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('06/15/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into TABLE1(ID, NM, STDATE, ENDATE)
Values(2, 2, TO_DATE('03/06/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('06/28/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
COMMIT;
查询是
with q1 as (
select id, nm, stdate, endate,
row_number() over (partition by id order by endate desc) as rn
from table1
) select * from q1 where rn=1
and <last5 months criteria using endate>;
查询结果
select id, nm, stdate, endate,
row_number() over (partition by id order by endate desc) as rn
from table1
将给出以下结果,然后您可以使用 rn 列和过去 5 个月的条件过滤结果。
id nm sdate endate rn
1 2 09.04.2013 17.06.2013 1
1 1 25.03.2013 14.06.2013 2
2 2 06.03.2013 28.06.2013 1
2 3 05.03.2013 15.06.2013 2