17,377
社区成员
发帖
与我相关
我的任务
分享
--楼主给的测试数据错了一个.
create table tb(time_id varchar2(6),value number);
insert into tb
select '200801',1 from dual union all
select '200802',2 from dual union all
select '200701',3 from dual union all
select '200702',4 from dual
select t.* ,
(select value from tb where time_id = (select max(time_id) from tb where time_id < t.time_id)) lastmonth_value,
(select value from tb where time_id = (select time_id from tb where to_number(substr(time_id,1,4)) = to_number(substr(t.time_id,1,4)) - 1 and substr(time_id,5,2) = substr(t.time_id,5,2))) lastyear_value
from tb t
order by t.time_id
drop table tb
/*
TIME_I VALUE LASTMONTH_VALUE LASTYEAR_VALUE
------ ---------- --------------- --------------
200701 3
200702 4 3
200801 1 4 3
200802 2 1 4
4 rows selected.
*/
select t.* ,
(select value from tb where time_id = (select max(time_id) from tb where time_id < t.time_id)) lastmonth_value,
(select value from tb where time_id = (select time_id from tb where to_number(substr(time_id,1,4)) = to_number(substr(t.time_id,1,4)) - 1 and substr(time_id,5,2) = substr(t.time_id,5,2))) lastyear_value
from tb t
order by t.time_id
select time_id,a.value as value , b.value as lastmonth_value ,c.value as lastyear_value
from test a , test b , test c
where a.time_id = '你指定的'
and b.time_id = a.time_id - 1个月
and c.time_id = a.time_id + 1个月
select time_id, value,lag(value,1) over(partition by substr(time_id,1,4)order by time_id)
as lastmonth_value,
lag(value,1) over(partition by substr(time_id,5,2) order by substr(time_id,1,4) ) as lastyear_value
from test