안녕하세요 오랜만에 질문 남깁니다.ㅜㅜ
with tt as( select 'test1' title,'Y' new_yn,'Y' hot_yn,null best_yn,'2015-01-01' reg_dt from dual union all select 'test2' ,'Y','Y','Y','2015-01-02' from dual union all select 'test3' ,'Y','Y','Y','2015-01-02' from dual union all select 'test4' ,'Y','Y',null,'2015-01-03' from dual union all select 'test5' ,null,'Y','Y','2015-01-03' from dual union all select 'test6' ,'Y','Y','Y','2015-01-04' from dual union all select 'test7' ,'Y',null,'Y','2015-01-04' from dual union all select 'test8' ,'Y','Y','Y','2015-01-01' from dual )
이런 데이터가 있는데요 제가 가져오고 싶은 데이터는
최근에 등록된 데이터중
new_yn='Y'인 데이터2개
hot_yn ='Y'인 데이터 3개
best_yn ='Y'인 데이터 2개 를뽑고 싶습니다.
결과화면
TITLE | COL1 | COL2 | COL3 |
TEST6 | NEW_YN | Y | 2015-01-04 |
TEST7 | NEW_YN | Y | 2015-01-04 |
TEST6 | HOT_YN | Y | 2015-01-04 |
TEST5 | HOT_YN | Y | 2015-01-03 |
TEST4 | HOT_YN | Y | 2015-01-03 |
TEST6 | BEST_YN | Y | 2015-01-04 |
TEST7 | BEST_YN | Y | 2015-01-04 |
SELECT * FROM ( SELECT TITLE ,'NEW_YN' COL1,NEW_YN COL2 ,REG_DT COL3,ROW_NUMBER() OVER(ORDER BY REG_DT DESC) RNUM FROM TT WHERE NEW_YN = 'Y' ) WHERE RNUM <=2 UNION ALL SELECT * FROM ( SELECT TITLE ,'HOT_YN' COL1,HOT_YN COL2 ,REG_DT COL3,ROW_NUMBER() OVER(ORDER BY REG_DT DESC) RNUM FROM TT WHERE HOT_YN = 'Y' ) WHERE RNUM <=3
UNION ALL 방법 말고 다른 방법은 없나요??
감사합니다.
추가:hot_yn='Y' 값이 3개가 없고 2개만 있다면 2개만 나와야 합니다.
SELECT title, col1, col2, col3 FROM (SELECT title, col1, col2, reg_dt col3 , ROW_NUMBER() OVER( PARTITION BY col1 ORDER BY reg_dt DESC -- 중복값만으로 정렬시 잘못된 결과가 나올 수 있습니다. , title DESC -- 유니크 정렬기준을 추가하세요. ) rn FROM tt UNPIVOT (col2 FOR col1 IN (new_yn, hot_yn, best_yn)) WHERE col2 = 'Y' ) WHERE rn <= DECODE(col1, 'NEW_YN', 2, 'HOT_YN', 3, 'BEST_YN', 2) ;