create table ValTable as
select to_date('2007/10/10','yyyy/mm/dd') as day1,10 as Val from dual
union select to_date('2007/10/11','yyyy/mm/dd'), 20 from dual
union select to_date('2007/10/12','yyyy/mm/dd'), 40 from dual
union select to_date('2007/10/30','yyyy/mm/dd'), 80 from dual
union select to_date('2007/11/10','yyyy/mm/dd'),160 from dual
union select to_date('2007/11/11','yyyy/mm/dd'),320 from dual
union select to_date('2007/11/12','yyyy/mm/dd'),640 from dual
union select to_date('2007/12/12','yyyy/mm/dd'),100 from dual
union select to_date('2007/12/15','yyyy/mm/dd'),900 from dual
union select to_date('2008/02/01','yyyy/mm/dd'),300 from dual
union select to_date('2008/02/03','yyyy/mm/dd'),400 from dual
union select to_date('2008/02/19','yyyy/mm/dd'),800 from dual
union select to_date('2008/02/28','yyyy/mm/dd'),900 from dual
union select to_date('2008/03/10','yyyy/mm/dd'),100 from dual
union select to_date('2008/03/15','yyyy/mm/dd'),300 from dual
union select to_date('2008/03/20','yyyy/mm/dd'),500 from dual
union select to_date('2008/04/20','yyyy/mm/dd'), 20 from dual
union select to_date('2008/04/21','yyyy/mm/dd'),200 from dual
union select to_date('2008/05/20','yyyy/mm/dd'),800 from dual;
select Day1,Val,SumVal,
nvl(max(SumVal) over(order by Rank
range between 2 preceding
and 2 preceding),0) as "2ヵ月前",
nvl(max(SumVal) over(order by Rank
range between 1 preceding
and 1 preceding),0) as "1ヵ月前",
nvl(max(SumVal) over(order by Rank
range between 1 following
and 1 following),0) as "1ヵ月後",
nvl(max(SumVal) over(order by Rank
range between 2 following
and 2 following),0) as "2ヵ月後"
from (select Day1,Val,
sum(Val) over(partition by trunc(Day1,'mm')) as SumVal,
dense_Rank() over(order by trunc(Day1,'mm')) as Rank
from ValTable)
order by Day1;