![](/img/trans.png)
[英]Oracle SQL: Update a table with data from another columns of the same table
[英]Oracle SQL - look up 2 columns from another table
我有2张桌子
Reg_table
student_ID Course_ID **Register**_status
1 co_01 enrolled
2 co_03 pending
3 co_05 cancelled
4 co_06 enrolled
Compl_table
student_ID Course_ID **Completion**_status
1 co_01 Attended
1 co_03
3 co_05
4 co_06 Attended
4 co_05
6 co_05
我想基于两个表的'Student_ID'和'Course_ID'的组合,从'Compl_table'中查找一个新状态,作为'Final_status'添加到Reg_table中。 例如,*如果一名学生在co_01上“注册”,然后在co_01上“参加”,则最终状态应为“参加”; *如果“ completion_status”为空白或“ Compl_table”中不存在“ Student_ID”和“ Course_ID”的组合,则最终状态应与“ Register_status”相同,即“已注册”,“待处理”或“已取消” ”。
因此,结果表应如下所示:
student_ID Course_ID **Final**_status
1 co_01 Attended 2 co_03 pending 3 co_05 cancelled 4 co_06 Attended
这可能吗? 提前致谢。
添加了代码(抱歉,该示例比示例复杂得多)
with reg_table as
(select
b.schd_id
,b.DMN_ID
,b.ACT_CPNT_ID
,b.CPNT_TYP_ID
,b.SCHD_DESC
,b.FACILITY_ID
,a.STUD_ID
,a.ENRL_STAT_ID
,a.ENRL_DTE
,c.CMPL_STAT_ID
from
PA_ENROLL_SEAT a
,PA_SCHED b
,pa_cpnt_evthst c
where
a.schd_id = b.schd_id
and
b.ACT_CPNT_ID = c.CPNT_ID(+)
and
a.STUD_ID = c.STUD_ID(+)
)
update reg_table r
set CMPL_STAT_ID = (select CMPL_STAT_ID from pa_cpnt_evthst c where
c.stud_id = a.stud_id and c.CPNT_ID = b.ACT_CPNT_ID)
where exists (select 1
from pa_cpnt_evthst c
where c.stud_id = a.stud_id and
c.CPNT_ID = b.ACT_CPNT_ID and
c.CMPL_STAT_ID is not null
)
在Oracle中,您可以执行以下操作:
update reg_table r
set register_status = (select c.completion_status
from compl_table c
where c.student_id = r.student_id and
c.course_id = r.course_id
)
where exists (select 1
from compl_table c
where c.student_id = r.student_id and
c.course_id = r.course_id and
c.completion_status is not null
);
检查是否可行:
Select r.student_ID, r.Course_ID, nvl(c.Completion_status, r.Register_status) as Final_status
From Reg_table R
left outer join Compl_table C on c.student_ID = r.student_ID and c.Course_ID = r.Course_ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.