这似乎是一个有点复杂,所以我会对改进感兴趣。
select distinct emp_id,
nvl(x_start_date,
lag(x_start_date)
over (partition by emp_id
order by rn)) as start_date,
nvl(x_end_date,
lead(x_end_date)
over (partition by emp_id
order by rn nulls first))
as end_date,
rating,
department
from (
select emp_id, start_date, end_date, rating, department,
case start_date
when lag(end_date)
over (partition by emp_id, rating, department
order by start_date) then null
else start_date end as x_start_date,
case end_date
when lead(start_date)
over (partition by emp_id, rating, department
order by start_date) then null
else end_date end as x_end_date,
rownum as rn
from table1
)
where x_start_date is not null or x_end_date is not null
order by emp_id, start_date
/
有了这个测试数据:
EMP_ID START_DA END_DATE RA DEPARTMENT SALARY
---------- -------- -------- -- -------------------- ----------
2000 01012010 01012011 A HR 9000
2000 01012011 01012012 A HR 10000
2000 01012012 01012013 A+ HR 20000
2000 01012013 01012014 A HR 20000
2000 01012014 12319999 A HR 21000
3000 01012011 01012012 B Operations 50000
3000 01012012 12319999 B Operations 60000
4000 07012011 07012012 B Operations 50000
4000 07012012 07012013 B Operations 50000
4000 07012013 12319999 B Operations 60000
我得到这个:
EMP_ID START_DA END_DATE RA DEPARTMENT
---------- -------- -------- -- --------------------
2000 01012010 01012012 A HR
2000 01012012 01012013 A+ HR
2000 01012013 12319999 A HR
3000 01012011 12319999 B Operations
4000 07012011 12319999 B Operations
我还与emp_id
(4000
)试过有三个连续的日期范围,并处理确定 - 外层where
子句使中间条目基本消失。 编辑为添加:现在也适用于2000/A
的额外日期范围,因为我在lead
//lag
分区中修正了排序。
内部查询空白出所有但第一开始日期和最后结束日期的连续块,并且外查询使用一第二轮lead
和lag
将它们合并到相同的行,其distinct
然后崩溃。
我假设start_date
和end_date
是DATE
领域,不VARCHAR2
,你必须NLS_DATE_FORMAT
设置为MMDDYYYY
。如果将它们存储为字符串,这是一个糟糕的主意,您需要在相当多的地方使用to_date()
才能使订购正常工作。
任何帮助家伙..我真的很努力解决这个问题.. – javanoob 2012-07-06 14:13:30