입고 Table
입고순번 | 입고일자 | 입고수량 | 입고단가 |
1 | 20150101 | 50 | 34500 |
2 | 20150103 | 36 | 35000 |
3 | 20150104 | 51 | 36000 |
4 | 20150115 | 36 | 35000 |
5 | 20150117 | 5 | 35000 |
출고테이블
출고순번 | 출고일자 | 출고수량 |
1 | 20150109 | 30 |
2 | 20150110 | 21 |
3 | 20150110 | 24 |
4 | 20150120 | 24 |
5 | 20150123 | 18 |
6 | 20150123 | 15 |
선입선출 소진 Table
출고번호 | 출고수량 | 입고일자 | 출고일자 | 소진수량 | 입고번호 | 시점재고 |
1 | 30 | 20150101 | 20150109 | 30 | 1 | 107 |
2 | 24 | 20150101 | 20150110 | 20 | 1 | 87 |
2 | 24 | 20150101 | 20150110 | 4 | 2 | 83 |
3 | 21 | 20150103 | 20150110 | 21 | 2 | 62 |
4 | 24 | 20150103 | 20150120 | 11 | 2 | 92 |
4 | 24 | 20150104 | 20150120 | 13 | 3 | 79 |
5 | 15 | 20150104 | 20150123 | 15 | 3 | 64 |
6 | 18 | 20150104 | 20150123 | 18 | 3 | 46 |
이런 식으로 데이터를 출력해야 하는데요...
입고 수량에서 순차적으로 출고수량을 빼서 소진 Table을 만드는 문제 입니다.
고수님들 의견 바랍니다....
WITH t_in AS ( SELECT 1 no, '20150101' dt, 50 qty, 34500 amt FROM dual UNION ALL SELECT 2, '20150103', 36, 35000 FROM dual UNION ALL SELECT 3, '20150104', 51, 36000 FROM dual UNION ALL SELECT 4, '20150115', 36, 35000 FROM dual UNION ALL SELECT 5, '20150117', 5, 35000 FROM dual ) , t_out AS ( SELECT 1 no, '20150109' dt, 30 qty FROM dual UNION ALL SELECT 2, '20150110', 24 FROM dual UNION ALL SELECT 3, '20150110', 21 FROM dual UNION ALL SELECT 4, '20150120', 24 FROM dual UNION ALL SELECT 5, '20150123', 15 FROM dual UNION ALL SELECT 6, '20150123', 18 FROM dual ) SELECT o.no AS o_no , o.qty AS o_qty , i.dt AS i_dt , o.dt AS o_dt , LEAST( i.qty , o.qty , i.s_qty - o.s_qty + o.qty , o.s_qty - i.s_qty + i.qty ) AS qty , i.no AS i_no , (SELECT SUM(qty) FROM t_in WHERE dt <= o.dt) - SUM( LEAST( i.qty , o.qty , i.s_qty - o.s_qty + o.qty , o.s_qty - i.s_qty + i.qty ) ) OVER(ORDER BY i.no, o.no) AS j_qty FROM (SELECT no, dt, qty , SUM(qty) OVER(ORDER BY no) s_qty FROM t_out ) o , (SELECT no, dt, qty, amt , SUM(qty) OVER(ORDER BY no) s_qty FROM t_in ) i WHERE i.s_qty > o.s_qty - o.qty AND o.s_qty > i.s_qty - i.qty ORDER BY i.no, o.no ;