WITH t1("품목", "금액", "적용일") AS ( SELECT '사과', '2000', '2013-01-01' FROM dual UNION ALL SELECT '사과', '3000', '2013-02-01' FROM dual UNION ALL SELECT '키위', '2000', '2013-01-01' FROM dual UNION ALL SELECT '키위', '4000', '2013-02-01' FROM dual ) ,t2("성명", "구입일", "품목") AS ( SELECT 'A', '2013-06-05', '사과' FROM dual UNION ALL SELECT 'A', '2013-06-05', '키위' FROM dual UNION ALL SELECT 'B', '2013-01-03', '사과' FROM dual UNION ALL SELECT 'B', '2013-01-03', '키위' FROM dual ) SELECT t2.* , (SELECT MIN(금액) KEEP (DENSE_RANK LAST ORDER BY 적용일) FROM t1 WHERE t1.품목 = t2.품목 AND t1.적용일 <= t2.구입일) "금액" FROM t2
WITH MT(PRD, PRI, APY) AS ( SELECT '사과', 2000, '2013-01-01' FROM DUAL UNION ALL SELECT '사과', 3000, '2013-02-01' FROM DUAL UNION ALL SELECT '키위', 2000, '2013-01-01' FROM DUAL UNION ALL SELECT '키위', 4000, '2013-02-01' FROM DUAL ), TT(NM, ORD, PRD) AS ( SELECT 'A', '2013-06-05', '사과' FROM DUAL UNION ALL SELECT 'A', '2013-06-05', '키위' FROM DUAL UNION ALL SELECT 'B', '2013-01-03', '사과' FROM DUAL UNION ALL SELECT 'B', '2013-01-03', '키위' FROM DUAL ) SELECT TT.NM, TT.PRD, TT.ORD, MAX(PRI) FROM MT, TT WHERE MT.PRD(+) = TT.PRD AND MT.APY(+) <= TT.ORD GROUP BY TT.NM, TT.PRD, TT.ORD ORDER BY TT.NM
--다시 작성합니다. --디케이님과 다른 방법으로 해볼려고 했는데 생각보다 어렵네요. ㅋㅋ --아무튼 저라면 디케이님거 쓰겠습니다. WITH TT(PRD, PRI, APY) AS ( SELECT '사과', 2000, '2013-01-01' FROM DUAL UNION ALL SELECT '사과', 3000, '2013-02-01' FROM DUAL UNION ALL SELECT '키위', 2000, '2013-01-01' FROM DUAL UNION ALL SELECT '키위', 4000, '2013-02-01' FROM DUAL ), MT(NM, ORD, PRD) AS ( SELECT 'A', '2013-06-05', '사과' FROM DUAL UNION ALL SELECT 'A', '2013-06-05', '키위' FROM DUAL UNION ALL SELECT 'B', '2013-01-03', '사과' FROM DUAL UNION ALL SELECT 'B', '2013-01-03', '키위' FROM DUAL ) SELECT * FROM ( SELECT MT.*, DECODE(MAX(APY) OVER(PARTITION BY NM, TT.PRD ORDER BY APY DESC), APY, PRI, 0) AS MDT FROM MT LEFT OUTER JOIN TT ON (MT.PRD = TT.PRD AND TT.APY <= MT.ORD) ) WHERE NVL(MDT, 1) != 0