我有一个表格,其中包含工作的开始和结束日期,如下所示:
EEID | EMP_START_DATE | EMP_TERM_DATE
-----+----------------+---------------
1 | 2014-01-01 | null
1 | null | 2014-03-30
1 | 2014-06-01 | null
1 | null | 2014-12-31
1 | 2015-08-01 | null
2 | 2001-07-01 | null
3 | 2010-03-01 | null
3 | null | 2010-03-30
3 | 2010-04-01 | null
3 | null | 2010-04-30
我想按照雇员ID(EEID)和就业期限对它进行如下转换:
EEID | EMP_START_DATE | EMP_TERM_DATE
-----+----------------+---------------
1 | 2014-01-01 | 2014-03-30
1 | 2014-06-01 | 2014-12-31
1 | 2015-08-01 | null
2 | 2001-07-01 | null
3 | 2010-03-01 | 2010-03-30
3 | 2010-04-01 | 2010-04-30
问题
有人可以告诉我该怎么做吗?
答案 0 :(得分:2)
一种方法是条件聚合。这需要枚举开始和结束,然后使用此枚举进行汇总:
select eeid, max(emp_start_date) as emp_start_date,
max(emp_end_date) as emp_end_date
from (select t.*,
(case when emp_start_date is not null
then count(emp_start_date) over (partition by eeid order by emp_start_date)
else count(emp_end_date) over (partition by eeid order by emp_send_date)
end) as seqnum
from t
) t
group by eeid, seqnum;
答案 1 :(得分:1)
当当前行为空时,可以使用超前和滞后获取前/后日期值:
select eeid,
emp_start_date as orig_start_date,
emp_term_date as orig_term_date,
coalesce(emp_start_date,
lag(emp_start_date)
over (partition by eeid order by coalesce(emp_start_date, emp_term_date)))
as emp_start_date,
coalesce(emp_term_date,
lead(emp_term_date)
over (partition by eeid order by coalesce(emp_term_date, emp_start_date)))
as emp_term_date
from your_table
order by eeid, emp_start_date, orig_start_date, emp_term_date, orig_term_date;
EEID ORIG_START_DATE ORIG_TERM_DATE EMP_START_DATE EMP_TERM_DATE
---------- --------------- -------------- -------------- -------------
1 2014-01-01 2014-01-01 2014-03-30
1 2014-03-30 2014-01-01 2014-03-30
1 2014-06-01 2014-06-01 2014-12-31
1 2014-12-31 2014-06-01 2014-12-31
1 2015-08-01 2015-08-01
2 2001-07-01 2001-07-01
3 2010-03-01 2010-03-01 2010-03-30
3 2010-03-30 2010-03-01 2010-03-30
3 2010-04-01 2010-04-01 2010-04-30
3 2010-04-30 2010-04-01 2010-04-30
,然后消除重复项:
select distinct eeid,
coalesce(emp_start_date,
lag(emp_start_date)
over (partition by eeid order by coalesce(emp_start_date, emp_term_date)))
as emp_start_date,
coalesce(emp_term_date,
lead(emp_term_date)
over (partition by eeid order by coalesce(emp_term_date, emp_start_date)))
as emp_term_date
from your_table
order by eeid, emp_start_date;
EEID EMP_START_DATE EMP_TERM_DATE
---------- -------------- -------------
1 2014-01-01 2014-03-30
1 2014-06-01 2014-12-31
1 2015-08-01
2 2001-07-01
3 2010-03-01 2010-03-30
3 2010-04-01 2010-04-30