间隔日期使用间隔

时间:2018-11-07 11:19:07

标签: sql oracle join

我有两个表,一个表用于所有员工的职业,第二个表用于工作期间的所有中断

这是我的餐桌员工职业生涯的结构:

startDate    endDate    year    codeMission  employeNumber  type
 ---------- ---------------------------------------------------
 2001-01-01 2001-12-31   2001     Tx100       N120        work
 2002-01-01 2002-12-31   2002     Tx100       N120        work

这是我的表中断的结构

startDate     endDate    year   codeMission   employeNumber    type
 ---------- ---------------------------------------------------------
 2001-07-01 2002-04-10   2001     Tx100       N120         interpption

现在我想创建一个新表,该表包含所有员工的职业而没有中断时间,这是我的示例

我想要这样的决赛桌:

startDate  endDate    year codeMission employeNumber     type
 ---------- --------------------------------------------
 2001-01-01 2001-06-31 2001     Tx100       N120         work
 2001-07-01 2002-04-10 2001     Tx100       N120         interpption
 2002-04-11 2002-12-31 2002     Tx100       N120         work

startDate  endDate    year codeMission employeNumber     type
 ---------- --------------------------------------------
 2001-01-01 2001-06-31 2001     Tx100       N120         work
 2001-07-01 2001-12-31 2001     Tx100       N120         interpption
 2002-01-01 2002-04-10 2002     Tx100       N120         interpption
 2002-04-11 2002-12-31 2002     Tx100       N120         work

1 个答案:

答案 0 :(得分:0)

我在此遵循的步骤是,如果将数据插入到新表中,则在中断表a中有条目时更新开始和结束日期

 INSERT INTO NewTable
 SELECT NVL(i2.endDate+1,e.startDate) AS startDate
        ,NVL(i1.startDate-1,e.endDate) AS endDate    
        ,e.year
        ,e.codeMission
        ,e.employeNumber
        ,e.type
 FROM Employee e
 LEFT JOIN Interruption i1 ON e.employeNumber=i1.employeNumber AND YEAR(e.startDate)=YEAR(i1.startDate)
 LEFT JOIN Interruption i2 ON e.employeNumber=i1.employeNumber AND YEAR(e.endDate)=YEAR(i2.endDate)

现在我们已经转换了employee表中的数据以使其与中断表匹配,因此现在我们将数据移至中断表中

 INSERT INTO NewTable
 SELECT startDate
        ,endDate    
        ,year
        ,codeMission
        ,employeNumber
        ,type
 FROM Interruption