특정데이터 통합 쿼리 질문 0 2 1,933

by 청새치 [SQL Query] [2011.04.08 09:55:32]


with test_table as (
 select 1 as id, to_date('20050101','yyyymmdd') as start_date, to_date('20050831','yyyymmdd') as end_date, 'A' as flag_1 from dual union all
 select 1 as id, to_date('20050901','yyyymmdd') as start_date, to_date('20060531','yyyymmdd') as end_date, 'A' as flag_1 from dual union all
 select 1 as id, to_date('20060601','yyyymmdd') as start_date, to_date('20061031','yyyymmdd') as end_date, 'X' as flag_1 from dual union all
 select 1 as id, to_date('20061101','yyyymmdd') as start_date, to_date('20070430','yyyymmdd') as end_date, 'A' as flag_1 from dual union all
 select 2 as id, to_date('20080201','yyyymmdd') as start_date, to_date('20101231','yyyymmdd') as end_date, 'A' as flag_1 from dual union all
 select 2 as id, to_date('20110101','yyyymmdd') as start_date, to_date('20110331','yyyymmdd') as end_date, 'X' as flag_1 from dual union all
 select 2 as id, to_date('20110401','yyyymmdd') as start_date, to_date('20111231','yyyymmdd') as end_date, 'A' as flag_1 from dual union all
 select 3 as id, to_date('20010101','yyyymmdd') as start_date, to_date('20101130','yyyymmdd') as end_date, 'A' as flag_1 from dual union all
 select 3 as id, to_date('20101201','yyyymmdd') as start_date, to_date('20110731','yyyymmdd') as end_date, 'A' as flag_1 from dual   
 )
select id, start_date, end_date
  from test_table
 where id = 1
   and flag_1 <> 'X'
 order by id, start_date


의 결과는

id start_date end_date
---------------------------------
1 2005-01-01 2005-08-31
1 2005-09-01 2006-05-31
1 2006-11-01 2007-04-30

입니다.

제가 원하는 결과는 falg_1 값의 조건으로 인해 빠진 레코드가 생겨도
레코드의 start_date 와 end_date가 연결이 되는것입니다.(앞레코드의 end_date 값 변경)

id start_date end_date
---------------------------------
1 2005-01-01 2005-08-31
1 2005-09-01 2006-10-31
1 2006-11-01 2007-04-30

어떤식으로 풀어나가면 위와 같은 결과를 얻을 수 있을까요?
힌트를 좀 주시면 연구해 보겠습니다.

감사합니다~

by 마농 [2011.04.08 10:20:55]
SELECT id
, start_date
, LEAD(start_date-1, 1, end_date) OVER(PARTITION BY id ORDER BY start_date) end_date
FROM test_table
WHERE id = 1
AND flag_1 <> 'X'
;

by 청새치 [2011.04.08 11:18:15]
유용한 분석함수가 있었군요.
마농님 감사합니다.
댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입