by 구들 [Oracle 기초] with order by rownum [2018.02.25 14:48:14]
안녕하세요? 급질문이 있어서 휴일에 문을 두드립니다. ㅜ.ㅜ
아래질문에 대한 쿼리를 짜려고하는데.. 초보라서. 어떻게 짜야할지 모르겠습니다.
그냥 상상코딩 한 건데.. 결과는 1개만 나올 듯 합니다.
모든 회원의 각각 '같음'/'다름' 결과를 보고 싶습니다..
바쁜시간 내서 읽어주셔서 감사합니다.
1. 각 회원(300만명) 은 배송지를 여러개(1~100개) 가지고 있습니다.
2. 각 배송지는 우편번호 기준으로 여러개(150개)의 업체가 관리합니다.
3. 업체는 업체번호를 가지고 있습니다.
4. 각 회원이 마지막으로 변경한 배송지의 업체번호가 높은것, 낮은것이 같으면 '같음' 다르면 '다름' 이라고 출력 합니다.
## 첫번째방식
with tu as (
select '111' user_id from dual union all
select '222' user_id from dual union all
select '333' user_id from dual union all
select '444' user_id from dual union all
select '555' user_id from dual
)
select user_id,
case when
(select delivery_seq s1 from (select user_id, delivery_seq from delivery ud, zip , tu where ud.user_id = tu.user_id and ud.zipno= zip.zipno order by ud.last_dt desc, zip.seq asc, ud.delivery_seq asc) where rownum=1)
= (select delivery_seq s2 from (select user_id, delivery_seq from delivery ud, zip , tu where ud.user_id = tu.user_id and ud.zipno= zip.zipno order by ud.last_dt desc, zip.seq desc, ud.delivery_seq asc) where rownum=1)
then '같음'
else '다름'
end delivery_result
from tu;
## 두번째방식
with tu as (
select '111' user_id from dual union all
select '222' user_id from dual union all
select '333' user_id from dual
)
select user_id,
case when s1.delivery_seq=s2.delivery_seq
then '같음'
else '다름'
end delivery_result
from tu,
(select * from (select user_id, delivery_seq from delivery ud, zip , tu where ud.user_id = tu.user_id and ud.zipno= zip.zipno order by ud.last_dt desc, zip.seq asc, ud.delivery_seq asc) where rownum=1) s1,
(select * from (select user_id, delivery_seq from delivery ud, zip , tu where ud.user_id = tu.user_id and ud.zipno= zip.zipno order by ud.last_dt desc, zip.seq desc, ud.delivery_seq asc) where rownum=1) s2
where tu.user_id=s1.user_id
and tu.user_id=s2.user_id
;
아래와 같이 궁금한 것이 해결 되었습니다.
이곳 사이트에서 해결책을 찾았습니다.
위 글을 읽어주셔서 감사합니다..
with A as (
select '111' user_id from dual union all
select '222' user_id from dual union all
select '333' user_id from dual union all
select '444' user_id from dual union all
select '555' user_id from dual
), B as (
select '111' user_id, '1' delivery_seq from dual union all
select '111' user_id, '2' delivery_seq from dual union all
select '111' user_id, '4' delivery_seq from dual union all
select '333' user_id, '1' delivery_seq from dual union all
select '444' user_id, '3' delivery_seq from dual union all
select '555' user_id, '2' delivery_seq from dual union all
select '555' user_id, '3' delivery_seq from dual
)
select * from
(
select A.user_id
,( with C as (select * from B group by user_id , delivery_seq order by user_id asc, delivery_seq desc)
select C.delivery_seq
from C
where C.user_id=A.user_id
and rownum=1
)as Result1
,( with C as (select * from B group by user_id , delivery_seq order by user_id asc, delivery_seq asc)
select C.delivery_seq
from C
where C.user_id=A.user_id
and rownum=1
)as Result2
from A
) T
where T.result1=T.result2;