안녕하세요
TABLE이
CODE, YYYY, MM으로 구성되어 있는 테이블입니다.
이번달이 2014, 02월인데
이번달 이전의 최신값을 찾아오고 싶은데 방법이 있을가요?
아무리 머리를 굴려봐도 답이 안나오네요
고수님들의 고언을 부탁드리겠습니다.
행복한 하루 되세요
YYYY, MM 2개를 정렬 조건으로 넣고 2번째 것을 조회되게 하였습니다.
WITH T1 AS ( SELECT '1' AS CODE, '2013' AS YYYY, '01' AS MM FROM DUAL UNION ALL SELECT '2' AS CODE, '2013' AS YYYY, '02' AS MM FROM DUAL UNION ALL SELECT '3' AS CODE, '2013' AS YYYY, '03' AS MM FROM DUAL UNION ALL SELECT '4' AS CODE, '2013' AS YYYY, '04' AS MM FROM DUAL UNION ALL SELECT '5' AS CODE, '2013' AS YYYY, '05' AS MM FROM DUAL UNION ALL SELECT '6' AS CODE, '2014' AS YYYY, '02' AS MM FROM DUAL ) SELECT * FROM ( SELECT CODE , YYYY , MM , ROW_NUMBER() OVER (ORDER BY YYYY DESC, MM DESC) AS RN FROM T1 ) WHERE RN = 2 ;
이번달 이전에 대한 조건까지 넣으시려면 WHERE 조건이 추가됩니다.
WITH T1 AS ( SELECT '1' AS CODE, '2013' AS YYYY, '01' AS MM FROM DUAL UNION ALL SELECT '2' AS CODE, '2013' AS YYYY, '02' AS MM FROM DUAL UNION ALL SELECT '3' AS CODE, '2013' AS YYYY, '03' AS MM FROM DUAL UNION ALL SELECT '4' AS CODE, '2013' AS YYYY, '04' AS MM FROM DUAL UNION ALL SELECT '5' AS CODE, '2013' AS YYYY, '05' AS MM FROM DUAL UNION ALL SELECT '6' AS CODE, '2014' AS YYYY, '02' AS MM FROM DUAL ) SELECT * FROM ( SELECT CODE , YYYY , MM , ROW_NUMBER() OVER (ORDER BY YYYY DESC, MM DESC) AS RN FROM T1 WHERE YYYY||MM <= TO_CHAR(SYSDATE, 'YYYYMM') ) WHERE RN = 2 ;