예를들어
지역 접수월 접수물량
부산 1월 10
부산 2월 20
부산 3월 30
ㅇ이런 테이블이 있을때
로우넘버를 써서.
지역 접수월 접수물량 RN
부산 1월 10 1
부산 2월 20 2
부산 3월 30 3
으로 rn을 넣었을경우.
지역 접수월 접수물량 전월물량
부산 1월 10 -
부산 2월 20 10
부산 3월 30 20
로우넘버를 서브쿼리를 이용하여 전월물량을 가져오고 싶습니다.
물론 전월이 없는경우 -를 넣구요..Rn = 1 일경우가 되겠죠..
쿼리로 구성이 어렵네요..ㅠ 초보지만 질문 남깁니다.
이럴 때 쓰라고 있는 lag라는 window function이 있습니다.
with t as ( select '부산' rgn, '1월' mon, '10' qty from dual union all select '부산' rgn, '2월' mon, '20' qty from dual union all select '부산' rgn, '3월' mon, '30' qty from dual ) select rgn, mon, qty , nvl(lag(qty) over(partition by rgn order by mon),'-') bfqty from t
-- join 으로 풀자면..
-- with 절은 jkson것 빌렸음
with t as
(
select '부산' rgn, '1월' mon, '10' qty from dual union all
select '부산' rgn, '2월' mon, '20' qty from dual union all
select '부산' rgn, '3월' mon, '30' qty from dual
) , a as (
select t.*
, row_number() over(partition by rgn order by mon) rn
from t
)
select a.rgn "지역" , a.mon "접수월" , a.qty "접수물량" , nvl(b.qty,'-') "전월물량"
from a a left outer join a b
on a.rgn = b.rgn
and a.rn - 1 = b.rn
order by a.rgn , a.rn