2016-10-27 91 views
2

假設我有一張可以每月捕獲就業狀況的表格。 我有一個情景,員工從實習開始,回到學校並全職回來。查找每週快照的就業歷史記錄

理想情況下,我想沿線輸出,這幾乎是他/她的就業歷史記錄。

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

如果我們肯定知道emp loyee無法返回到先前的類型(例如,實習生 - > 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 
; 
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;