현재일 기준으로 6개월(2015.03.31~2015.09.30)에서 총 개월수를 구하는데 월이 같으면 1개월으로 계산을 하여
예)와 같이 결과를 얻는 쿼리를 문의 합니다.
예1) 결과는 7개월이 나와야 합니다.
WITH TT AS(
SELECT 1 AS 순번, '20140402' AS 시작일자, '99991231' AS 종료일자 FROM DUAL UNION ALL --201504, 201505, 201506, 201507, 201508, 201509
SELECT 2 AS 순번, '20140510' AS 시작일자, '00000000' AS 종료일자 FROM DUAL UNION ALL
SELECT 3 AS 순번, '20141210' AS 시작일자, '20150324' AS 종료일자 FROM DUAL UNION ALL
SELECT 4 AS 순번, '20140710' AS 시작일자, '20150510' AS 종료일자 FROM DUAL --201503, 201504, 201505
)
예2) 결과는 2개월이 나와야 합니다.
WITH TT AS(
SELECT 1 AS 순번, '20150410' AS 시작일자, '00000000' AS 종료일자 FROM DUAL UNION ALL
SELECT 2 AS 순번, '20150410' AS 시작일자, '20150420' AS 종료일자 FROM DUAL UNION ALL --201504
SELECT 3 AS 순번, '20150701' AS 시작일자, '20150720' AS 종료일자 FROM DUAL --201507
)
예3) 결과는 4개월이 나와야 합니다.
WITH TT AS(
SELECT 1 AS 순번, '20150410' AS 시작일자, '20150725' AS 종료일자 FROM DUAL UNION ALL --201504, 201505, 201506, 201507
SELECT 2 AS 순번, '20150410' AS 시작일자, '20150520' AS 종료일자 FROM DUAL --201504, 201505
)
예4) 결과는 3개월이 나와야 합니다.
WITH TT AS(
SELECT 1 AS 순번, '20150410' AS 시작일자, '20150515' AS 종료일자 FROM DUAL UNION ALL --201504, 201505
SELECT 2 AS 순번, '20150520' AS 시작일자, '20150720' AS 종료일자 FROM DUAL --201505, 201506, 201507
)
SELECT COUNT(DISTINCT lv) cnt FROM tt , (SELECT lv , TO_CHAR(DECODE(lv, 7, dt, TRUNC(dt, 'mm')), 'yyyymmdd') sdt , TO_CHAR(DECODE(lv, 1, dt, LAST_DAY(dt)) , 'yyyymmdd') edt FROM (SELECT LEVEL lv , ADD_MONTHS(sysdate, 1 - LEVEL) dt FROM dual CONNECT BY LEVEL <= 7 ) ) WHERE 시작일자 <= edt AND 종료일자 >= sdt ;