Search code examples
sqloracle-databaseoracle12c

How to create GROUP BY on min and max date


I have a database table like this

emp_id start-date  end_date    title    location
111    1-JAN-2000  31-DEC-2003 MANAGER  NYO
111    1-JAN-2003  31-DEC-2005 MANAGER  BOM
111    1-JAN-2006  31-DEC-2007 CFO      NYO
111    1-JAN-2008  31-DEC-2015 MANAGER  NYO

I have created a SQL code already with GROUP BY and min , max function

select emp_id,min(start_date),max(end_date),title
from table1
group by emp_id,title

What is expect is this:

111 1-JAN-2000 31-DEC-2005 MANAGER
111 1-JAN-2006 31-DEC-2007 CFO
111 1-JAN-2008 31-DEC-2015 MANAGER

What i am getting is:

111 1-JAN-2000 31-DEC-2015 MANAGER 
111 1-JAN-2006 31-DEC-2007 CFO

Solution

  • This is a type of gaps-and-islands problem with date-chains. I would suggest using a left join to find where the islands start. Then a cumulative sum and aggregation:

    select emp_id, title, min(start_date), max(end_date)
    from (select t.*,
                 sum(case when tprev.emp_id is null then 1 else 0 end) over
                     (partition by t.emp_id, t.title order by t.start_date) as grouping
          from t left join
               t tprev
               on t.emp_id = tprev.emp_id and
                  t.title = tprev.title and
                  t.start_date = tprev.end_date + 1
         ) t
    group by grouping, emp_id, title;