Skip to content
Advertisement

Joining two tables using left outer join and population a new column values based on the right table column

I have two tables exam_table and emp_table, Here i would like to join both tables using left outer join and I want to create a new column called new_column using exam_completed_date column from the right table.

select id, exam_completed_date from exam_table;

id exam_completed_date 
0  12-01-2019
1  12-12-2019

select id, week_end_date from emp_table where id=0;

id week_end_date
0  11-29-2019
0  11-30-2019
0  12-31-2019
0  12-01-2019
0  12-02-2019
0  12-03-2019
0  12-04-2019

select id, week_end_date, exam_completed_date 
from emp_table emp left outer join 
     exam_table exam 
     on (exam.id=emp.id and exam.exam_completed_date=emp.week_end_date)
where id=0

id week_end_date exam_completed_date 
0  11-29-2019    
0  11-30-2019
0  12-31-2019
0  12-01-2019     12-01-2019
0  12-02-2019    
0  12-03-2019    
0  12-04-2019   

I need output like this

id week_end_date exam_completed_date  new_column
0  11-29-2019    
0  11-30-2019
0  12-31-2019
0  12-01-2019     12-01-2019           12-01-2019
0  12-02-2019                          12-01-2019
0  12-03-2019                          12-01-2019 
0  12-04-2019                          12-01-2019    

Advertisement

Answer

I think you want a cumulative max window function:

select id, week_end_date, exam_completed_date,
       max(exam_completed_date) over (partition by id order by week_end_date) as newcolumn
from emp_table emp left outer join
     exam_table exam 
     on exam.id=emp.id and
        exam.exam_completed_date = emp.week_end_date
where id = 0;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement