假设我有一张能够按月记录就业状况的表格。 我有一个场景,一名员工从实习生开始,回到学校并全职回来。
理想情况下,我希望沿着一条线输出,这几乎是他/她的工作经历的历史。
date_hire date_termination employee_id employee_type
2012_01_01 2012_03_01 10002 intern
2012_05_01 null 10002 full-time
数据看起来像
date_snapshot date_hire date_termination employee_id employee_type
2012_01_01 2012_01_01 null 10002 intern
2012_02_01 2012_01_01 null 10002 intern
2012_03_01 2012_01_01 2012_03_01 10002 intern
2012_04_01 2012_01_01 2012_03_01 10002 intern
2012_05_01 2012_05_01 null 10002 full-time
2012_06_01 2012_05_01 null 10002 full-time
2012_07_01 2012_05_01 null 10002 full-time
......
我尝试使用GROUP BY技术
SELECT
date_hire,
date_termination,
employee_id,
employee_type
FROM
employees
GROUP BY
date_hire,
date_termination,
employee_id,
employee_type
给我回复,请注意我有一个不需要的记录
date_hire date_termination employee_id employee_type
2012_01_01 null 10002 intern
2012_01_01 2012_03_01 10002 intern
2012_05_01 null 10002 full-time
答案 0 :(得分:0)
如果我们确定员工无法返回之前的类型(例如实习生 - > AWF - >全职 - > AWF),那么有一个简单的解决方案:
select date_hire
,min (date_termination) as date_termination
,employee_id
,employee_type
from employees e
group by date_hire
,employee_id
,employee_type
;
否则 -
select date_hire
,date_termination
,employee_id
,employee_type
from (select e.*
,lead (date_hire) over (partition by e.employee_id order by date_snapshot) as next_date_hire
,lead (date_termination) over (partition by e.employee_id order by date_snapshot) as next_date_termination
,lead (employee_type) over (partition by e.employee_id order by date_snapshot) as next_employee_type
,max (date_snapshot) over (partition by e.employee_id) as max_date_snapshot
from employees e
)
where date_hire <> next_date_hire
or date_termination <> next_date_termination
or employee_type <> next_employee_type
or date_snapshot = max_date_snapshot
;
答案 1 :(得分:0)
以下查询还应提供您想要的输出。
SELECT DISTINCT MIN(date_hire) OVER (PARTITION BY employee_id,employee_type) date_hire,
MIN(date_termination) OVER (PARTITION BY employee_id,employee_type) date_termination,
employee_type,employee_id
FROM employees;