簡體   English   中英

使用左外連接連接兩個表並根據右表列填充新列值

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

我有兩個表 exam_table 和 emp_table,在這里我想使用左外連接連接兩個表,我想使用右表中的 exam_completed_date 列創建一個名為 new_column 的新列。

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   

我需要這樣的輸出

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    

我想你想要一個累積最大窗口函數:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM