create table Tabibito(
code number(1),
Year char(6),
kekka number(1));
insert into Tabibito Values(1,'200401',1);
insert into Tabibito Values(1,'200402',1);
insert into Tabibito Values(1,'200403',2);
insert into Tabibito Values(1,'200404',1);
insert into Tabibito Values(2,'200401',1);
insert into Tabibito Values(2,'200402',2);
insert into Tabibito Values(2,'200403',1);
insert into Tabibito Values(2,'200404',1);
insert into Tabibito Values(3,'200401',1);
insert into Tabibito Values(4,'200401',1);
insert into Tabibito Values(4,'200402',2);
insert into Tabibito Values(4,'200403',2);
insert into Tabibito Values(4,'200404',1);
insert into Tabibito Values(6,'200612',1);
insert into Tabibito Values(6,'200701',1);
insert into Tabibito Values(6,'200702',1);
insert into Tabibito Values(7,'200611',1);
insert into Tabibito Values(7,'200701',1);
insert into Tabibito Values(7,'200703',1);
insert into Tabibito Values(8,'200610',1);
insert into Tabibito Values(8,'200712',1);
insert into Tabibito Values(8,'200801',1);
insert into Tabibito Values(9,'200611',1);
insert into Tabibito Values(9,'200612',1);
insert into Tabibito Values(9,'200701',2);
commit;
--■■■旅人算の感覚を使わない方法■■■
select code,min(Year) as MinYear,max(Year) as MaxYear
from (select code,Year,kekka,willSum,
sum(willSum) over(partition by code order by Year) as GID
from (select code,Year,kekka,
case Lag(Year) over(partition by code order by Year)
when to_char(add_months(to_date(Year,'yyyymm'),-1),'yyyymm')
then 0 else 1 end as willSum
from Tabibito
where kekka = 1))
group by code,GID
order by code,GID;
--■■■旅人算の感覚を使う方法■■■
select code,min(Year) as MinYear,max(Year) as MaxYear
from (select code,Year,kekka,
to_number(substr(Year,1,4))*12+to_number(substr(Year,-2))
-Row_Number() over(partition by code order by Year) as GID
from Tabibito
where kekka = 1)
group by code,GID
order by code,GID;