아래 표는 결과값
PROD | Grade | D_DATE | S_DATE | QTY | INV |
Moringga | A+ | 20190617 | 20190723 | 5000 | OUT |
Moringga | A+ | 20190617 | 20190623 | 1500 | YES |
Moringga | A+ | 20190617 | 20190623 | 1000 | NO |
with t as ( select 'Moringga' prod, 'A+' grade, '20190617' d_date, '20190623' s_date, '5000' qty, 'OUT' inv from dual union all select 'Moringga', 'A+', '20190617', '20190623', '1000', 'YES' from dual union all select 'Moringga', 'A+', '20190618', '20190627', '1000', 'NO' from dual union all select 'Moringga', 'A+', '20190617', '20190623', '500', 'YES' from dual ) select * from t
예시 자료의 수치가 서로 맞지 않고요. 질문은 이해하기 어렵게 설명되고 있네요.
설명은 복잡하고 이해하기 어려운데? 그냥 단순하게 만들어 봤습니다.
이게 원하는 쿼리가 아닐수도 있겠네요.
SELECT prod , grade , d_date , DECODE(inv, 'OUT', TO_CHAR(ADD_MONTHS(TO_DATE(s_date, 'yyyymmdd'), 1), 'yyyymmdd'), s_date) s_date , SUM(qty) qty , inv FROM t GROUP BY prod, grade, d_date, s_date, inv ORDER BY prod, grade, d_date, s_date, inv ;
SELECT prod, grade, d_date, s_date, qty, inv , CASE WHEN inv = 'OUT' AND SUBSTR(s_date, 1, 6) = SUBSTR(MAX(CASE WHEN inv IN ('YES', 'NO') THEN s_date END) OVER(PARTITION BY prod), 1, 6) THEN TO_CHAR(ADD_MONTHS(TO_DATE(s_date, 'yyyymmdd'), 1), 'yyyymmdd') ELSE s_date END x FROM t ORDER BY d_date, s_date ;