col GID for a8
col score for 99999
col R1 for 99999
col R2 for 99999
col R3 for 99999
col R4 for 99999
--■■■decode関数を使う方■■■
select GID,score,
decode(rn,1,N1,2,P1,3,P2,4,P3,5,P4) as R1,
decode(rn,1,N2,2,N1,3,P1,4,P2,5,P3) as R2,
decode(rn,1,N3,2,N2,3,N1,4,P1,5,P2) as R3,
decode(rn,1,N4,2,N3,3,N2,4,N1,5,P1) as R4
from (select GID,score,
Row_Number() over(partition by GID order by score) as rn,
Lag(score,1,0) over(partition by GID order by score) as P1,
Lag(score,2,0) over(partition by GID order by score) as P2,
Lag(score,3,0) over(partition by GID order by score) as P3,
Lag(score,4,0) over(partition by GID order by score) as P4,
Lead(score,1,0) over(partition by GID order by score) as N1,
Lead(score,2,0) over(partition by GID order by score) as N2,
Lead(score,3,0) over(partition by GID order by score) as N3,
Lead(score,4,0) over(partition by GID order by score) as N4
from student)
order by GID,score;
--■■■マトリクス表を使う方■■■
select a.GID,a.score,
case when b.R1 > 0 then Lead(a.score,abs(b.R1),0) over(partition by a.GID order by a.score)
else Lag(a.score,abs(b.R1),0) over(partition by a.GID order by a.score) end as R1,
case when b.R2 > 0 then Lead(a.score,abs(b.R2),0) over(partition by a.GID order by a.score)
else Lag(a.score,abs(b.R2),0) over(partition by a.GID order by a.score) end as R2,
case when b.R3 > 0 then Lead(a.score,abs(b.R3),0) over(partition by a.GID order by a.score)
else Lag(a.score,abs(b.R3),0) over(partition by a.GID order by a.score) end as R3,
case when b.R4 > 0 then Lead(a.score,abs(b.R4),0) over(partition by a.GID order by a.score)
else Lag(a.score,abs(b.R4),0) over(partition by a.GID order by a.score) end as R4
from (select score,GID,
Row_Number() over(partition by GID order by score) as JoinKey
from student) a Join
(select 1 as JoinKey,1 as R1,2 as R2,3 as R3,4 as R4 from dual union all
select 2,-1, 1, 2, 3 from dual union all
select 3,-2,-1, 1, 2 from dual union all
select 4,-3,-2,-1, 1 from dual union all
select 5,-4,-3,-2,-1 from dual) b
using(JoinKey)
order by a.GID,a.score;