sql - 使用左外连接连接两个表并根据右表列填充新列值
问题描述
我有两个表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;
推荐阅读
- angularjs - 代理问题以及使用 Angular CLI 创建/运行 Angular 应用程序的问题
- c# - 如何从数据库中读取数据并存储到数组 C#
- php - file_put_contents 将坏字符保存到文件
- websocket - 如何使 websocket 流广播到许多其他页面?
- nginx - 带有 uwsgi、flask 和 slimxmpp 的 Nginx 服务器
- jquery - 使用 PivotTable.js 在总列中显示平均值
- excel - 如何阻止更改预先格式化的excel中的格式?
- r - “{123, affdsf, 223, 22, dgbwa, 33333}”的格式是什么?
- c# - 在 ASP.NET 中设置日常工作
- windows - Windows 10 平板电脑上的 Windows 窗体应用程序?