Merge date ranges

前端 未结 1 619
栀梦
栀梦 2021-01-18 15:05

Oracle SQL newbie here and first time poster.

I thought this would be simple until I realized I can\'t figure out how to split return assignments.

Here is my

1条回答
  •  清酒与你
    2021-01-18 15:42

    Employee A has two rows for 07-01-2013 through 08-10-2014; I assumed that is a mistake and I deleted one of the rows.

    Other than that, this is an application of the "tabibitosan method" for solving "gaps and islands" problems for date ranges. The trick is in creating the "groups" (gp) for adjacent intervals.

    with
         prep ( id, st_dt, end_dt, gp, pos, locn, status ) as (
           select id, st_dt, end_dt, 
                  end_dt - sum( end_dt - st_dt + 1 ) over (partition by id, pos, locn, status 
                                                           order by st_dt),
                  pos, locn, status
           from   asgn
         )
    select id, min(st_dt) as st_dt, max(end_dt) as end_dt, pos, locn, status
    from   prep
    group by id, gp, pos, locn, status
    order by id, st_dt
    ;
    
    
    
    ID         ST_DT      END_DT     POS        LOCN           STATUS
    ---------- ---------- ---------- ---------- ---------- ----------
    A          12-31-2006 08-16-2009 CLERK      LAX                 3
    A          08-17-2009 10-04-2009 CLERK      LAX                 0
    A          10-05-2009 04-09-2013 OPR        NYC                 3
    A          04-10-2013 08-10-2014 CLERK      LAX                 3
    B          04-10-2013 05-31-2013 SUP        LAX                 3
    B          06-01-2013 06-30-2014 SUP        LAX                 0
    B          07-01-2013 08-10-2014 SUP        LAX                 3
    B          08-11-2014 08-11-2014 CLERK      NYC                 3
    B          08-12-2014 02-10-2016 SUP        LAX                 3
    B          02-11-2016 08-12-2016 OPER       SFO                 3
    
     10 rows selected 
    

    0 讨论(0)
提交回复
热议问题