2016-07-24 46 views
0

我有兩個表,Job_Events和Comp_Events,具體如下:更新數據,並挑選最新/最早日期數據主表

Job_events 

userid eventstartdt   jobcode 
    10 2014-08-18 00:00:00 j1 
    10 2015-07-27 00:00:00 j1 
    10 2015-03-23 00:00:00 j2 
    10 2015-12-28 00:00:00 j3 
    10 2015-03-23 00:00:00 j4 
    10 2015-03-23 00:00:00 j5 

Comp_Events 

userid eventstartdt  salary 
    10 2014-08-11 00:00:00 1000 
    10 2015-03-23 00:00:00 1525 
    10 2015-06-21 00:00:00 500 
    10 2016-03-21 00:00:00 2000 

預期輸出:

jobcompevents 

userid jobeventstartdt  jobcode salary 
    10 2014-08-18 00:00:00 j1  1000 
    10 2015-07-27 00:00:00 j1   500 
    10 2015-03-23 00:00:00 j2  1525 
    10 2015-12-28 00:00:00 j3   500 
    10 2015-03-23 00:00:00 j4  1525 
    10 2015-03-23 00:00:00 j5  1525 

PS:我無法基於YYYYMM格式加入,因爲基於月份的數據可能不可用。我應該爲那份工作記錄挑選最新/最早的爭論點,以便它與一條記錄合併。

在此先感謝。

回答

0

我爲更多測試創建了更多輸入數據。查詢應該能夠將輸入(和輸出)分開userid,對於salary,它應該顯示NULL,開始日期在Comp_events表中userid的所有開始日期之前。

請注意,我編輯了您的文章以糾正大量的拼寫錯誤;如果這是直接來自你的實際設置,你將不得不在那裏糾正它們。

with 
    job_events (userid, eventstartdt, jobcode) as (
     select 10, date '2014-08-18', 'j1' from dual union all 
     select 10, date '2015-07-27', 'j1' from dual union all 
     select 10, date '2015-03-23', 'j2' from dual union all 
     select 10, date '2015-12-28', 'j3' from dual union all 
     select 10, date '2015-03-23', 'j4' from dual union all 
     select 10, date '2015-03-23', 'j5' from dual union all 
     select 35, date '2014-04-18', 'j1' from dual union all 
     select 35, date '2015-09-22', 'j1' from dual union all 
     select 35, date '2015-10-29', 'j8' from dual 
    ), 
    comp_events (userid, eventstartdt, salary) as (
     select 10, date '2014-08-11', 1000 from dual union all 
     select 10, date '2015-03-23', 1525 from dual union all 
     select 10, date '2015-06-21', 500 from dual union all 
     select 10, date '2016-03-21', 2000 from dual union all 
     select 35, date '2015-06-15', 2850 from dual 
    ), 
    u (userid, eventstartdt, jobcode, salary) as (
     select userid, eventstartdt, jobcode, null from job_events 
     union all 
     select userid, eventstartdt, null , salary from comp_events 
    ), 
    prep (userid, eventstartdt, jobcode, salary) as (
     select userid, eventstartdt, jobcode, 
       last_value(salary ignore nulls) over 
          (partition by userid order by eventstartdt) 
     from u 
    ) 
select userid, eventstartdt, jobcode, salary 
from  prep 
where jobcode is not null 
order by userid, jobcode, eventstartdt 
; 

輸出

USERID EVENTSTARTDT JOBCODE  SALARY 
---------- ------------ ------- ---------- 
     10 2014-08-18 j1   1000 
     10 2015-07-27 j1    500 
     10 2015-03-23 j2   1525 
     10 2015-12-28 j3    500 
     10 2015-03-23 j4   1525 
     10 2015-03-23 j5   1525 
     35 2014-04-18 j1 
     35 2015-09-22 j1   2850 
     35 2015-10-29 j8   2850 

9 rows selected. 
+0

太感謝你了, –