1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | WITH t1 AS ( SELECT 1 idx, 'AA' scd, 'A스타일' snm, '011' ccd, 'BEIGE' cnm, 0 rfid, 100 sz, 1 cnt, 'GG' box FROM dual UNION ALL SELECT 2, 'BB' , 'B스타일' , '012' , 'CHARCOAL' , 0, 200, 3, 'GG' FROM dual UNION ALL SELECT 3, 'CC' , 'C스타일' , '013' , 'OMAHA BEIGE' , 0, 300, 1, 'GG' FROM dual UNION ALL SELECT 4, 'DD' , 'D스타일' , '014' , 'IVORY' , 0, 400, 1, 'GG' FROM dual UNION ALL SELECT 5, 'DD' , 'D스타일' , '014' , 'IVORY' , 0, 400, 1, 'GG' FROM dual ) , t2 AS ( SELECT 1 idx, 'AA' scd, 'A스타일' snm, '011' ccd, 'BEIGE' cnm, 0 rfid, 100 sz, 2 cnt, 'GG' box FROM dual UNION ALL SELECT 2, 'BB' , 'B스타일' , '012' , 'CHARCOAL' , 0, 200, 2, 'GG' FROM dual UNION ALL SELECT 3, 'CC' , 'C스타일' , '013' , 'OMAHA BEIGE' , 0, 300, 0, 'GG' FROM dual UNION ALL SELECT 4, 'DD' , 'D스타일' , '014' , 'IVORY' , 0, 400, 3, 'GG' FROM dual ) SELECT a.idx idx_1 , b.idx idx_2 , a.scd, a.snm, a.ccd, a.cnm, a.rfid, a.sz, a.box , a.cnt cnt_1 , LEAST(a.cnt, NVL(b.cnt, 0) - a.s_cnt + a.cnt) cnt_2 FROM ( SELECT idx, scd, snm, ccd, cnm, rfid, sz, cnt, box , SUM (cnt) OVER(PARTITION BY scd ORDER BY idx) s_cnt FROM t1 ) a LEFT OUTER JOIN t2 b ON a.scd = b.scd AND a.s_cnt - a.cnt < b.cnt UNION ALL SELECT a.idx_1 , b.idx idx_2 , b.scd, b.snm, b.ccd, b.cnm, b.rfid, b.sz, b.box , b.cnt - NVL(a.s_cnt, 0) cnt_1 , b.cnt - NVL(a.s_cnt, 0) cnt_2 FROM ( SELECT scd , MAX (idx) + 0.1 idx_1 , SUM (cnt) s_cnt FROM t1 GROUP BY scd ) a RIGHT OUTER JOIN t2 b ON a.scd = b.scd WHERE b.cnt > NVL(a.s_cnt, 0) ORDER BY 1, 2 ; |