item_cd | start_dt | end_dt | sts |
a | 20010101 | 20010201 | S |
a | 20010201 | 20010301 | E |
a | 20010301 | 20010401 | E |
a | 20010501 | 99992131 | S |
b | 20010101 | 20010201 | S |
b | 20010201 | 20010301 | E |
b | 20010401 | 20010501 | S |
b | 20010501 | 20010601 | E |
결과값 |
|||
item_cd | start_dt | end_dt | |
a | 20010101 | 20010401 | |
a | 20010501 | 99991231 | |
b | 20010101 | 20010301 | |
b | 20010401 | 20010601 |
WITH t AS ( SELECT 'a' item_cd, '20010101' start_dt, '20010201' end_dt, 'S' sts FROM dual UNION ALL SELECT 'a', '20010201', '20010301', 'E' FROM dual UNION ALL SELECT 'a', '20010301', '20010401', 'E' FROM dual UNION ALL SELECT 'a', '20010501', '99992131', 'S' FROM dual UNION ALL SELECT 'b', '20010101', '20010201', 'S' FROM dual UNION ALL SELECT 'b', '20010201', '20010301', 'E' FROM dual UNION ALL SELECT 'b', '20010401', '20010501', 'S' FROM dual UNION ALL SELECT 'b', '20010501', '20010601', 'E' FROM dual ) -- 두가지 기준으로 문제를 풀 수 있겠네요. -- 1. start_dt, end_dt 를 기준으로 한 풀이 방법 -- SELECT item_cd , MIN(start_dt) start_dt , MAX(end_dt) end_dt FROM (SELECT item_cd, start_dt, end_dt, sts , SUM(flag) OVER(PARTITION BY item_cd ORDER BY start_dt) grp FROM (SELECT item_cd, start_dt, end_dt, sts , DECODE(LAG(end_dt) OVER(PARTITION BY item_cd ORDER BY start_dt) , start_dt, 0, 1) flag FROM t ) ) GROUP BY item_cd, grp ORDER BY item_cd, grp ; -- 2. sts 를 기준으로 한 풀이 방법 -- SELECT item_cd , MIN(start_dt) start_dt , MAX(end_dt) end_dt FROM (SELECT item_cd, start_dt, end_dt, sts , SUM(DECODE(sts, 'S', 1)) OVER(PARTITION BY item_cd ORDER BY start_dt) grp FROM t ) GROUP BY item_cd, grp ORDER BY item_cd, grp ;