WITH T AS ( SELECT '200909' PRD, 'A' GRP, '002' VER , '1' TRANS FROM DUAL UNION SELECT '200909' PRD, 'A' GRP, '004' VER , '2' TRANS FROM DUAL UNION SELECT '200909' PRD, 'A' GRP, '006' VER , '3' TRANS FROM DUAL UNION SELECT '200909' PRD, 'B' GRP, '004' VER , '2' TRANS FROM DUAL UNION SELECT '200909' PRD, 'B' GRP, '006' VER , '1' TRANS FROM DUAL UNION SELECT '201003' PRD, 'C' GRP, '002' VER , '1' TRANS FROM DUAL UNION SELECT '201003' PRD, 'C' GRP, '008' VER , '2' TRANS FROM DUAL)
위와 같은 테이블이 있을 때 PRD - GRP 별로 TRANS가 가장 높은 순위의 VER을 뽑아내고 싶습니다.
#결과
200909 A 006 3
200909 B 004 2
201003 C 008 2
MAX 함수를 가지고 짜려 했으나 잘 안되네요 ㅠ
조언 부탁드립니다.
WITH T AS ( SELECT '200909' PRD, 'A' GRP, '002' VER , '1' TRANS FROM DUAL UNION SELECT '200909' PRD, 'A' GRP, '004' VER , '2' TRANS FROM DUAL UNION SELECT '200909' PRD, 'A' GRP, '006' VER , '3' TRANS FROM DUAL UNION SELECT '200909' PRD, 'B' GRP, '004' VER , '2' TRANS FROM DUAL UNION SELECT '200909' PRD, 'B' GRP, '006' VER , '1' TRANS FROM DUAL UNION SELECT '201003' PRD, 'C' GRP, '002' VER , '1' TRANS FROM DUAL UNION SELECT '201003' PRD, 'C' GRP, '008' VER , '2' TRANS FROM DUAL) SELECT * FROM T WHERE (PRD,GRP,TRANS) IN (SELECT PRD,GRP,MAX(TRANS) FROM T GROUP BY PRD,GRP)
예전에 비슷한 질문을 게시판에서 봤던 기억이나서 마농님이 짜신 쿼리 보고 응용해봤습니다 ㅎㅎㅎ
WITH T AS ( SELECT '200909' PRD, 'A' GRP, '002' VER , '1' TRANS FROM DUAL UNION SELECT '200909' PRD, 'A' GRP, '004' VER , '2' TRANS FROM DUAL UNION SELECT '200909' PRD, 'A' GRP, '006' VER , '3' TRANS FROM DUAL UNION SELECT '200909' PRD, 'B' GRP, '004' VER , '2' TRANS FROM DUAL UNION SELECT '200909' PRD, 'B' GRP, '006' VER , '1' TRANS FROM DUAL UNION SELECT '201003' PRD, 'C' GRP, '002' VER , '1' TRANS FROM DUAL UNION SELECT '201003' PRD, 'C' GRP, '008' VER , '2' TRANS FROM DUAL) SELECT MAX(PRD) , MAX(GRP) , MAX(VER) KEEP (DENSE_RANK FIRST ORDER BY PRD , GRP , TRANS DESC) VER , MAX(TRANS) KEEP (DENSE_RANK FIRST ORDER BY PRD , GRP , TRANS DESC) TRANS FROM T GROUP BY PRD , GRP ORDER BY PRD , GRP