Merge SQL Tables

我的未来我决定 提交于 2021-01-29 19:30:11

问题


I have two tables, which have the same columns except for 1. So for example:

Table1 (column names): Student | Course | Exam1 | Exam2
Table2 (column names): Student | Course | Exam3 | FinalExam

I would like to combine these two tables to get:

Table: Student | Course | Exam1 | Exam2 | FinalExam

I have something along the following:

Select
    student,
    course,
    Exam1, 
    Exam2
From Table1

Select
    student,
    course,
    Exam3, 
    FinalExam
From Table2


Select
    student,
    course,
    Coalesce( t1.Exam1, 0) as Exam1 
    Coalesce( t1.Exam2, 0) as Exam2
    Coalesce( t2.Exam3, 0) as Exam3
    Coalesce( t2.FinalExam, 0) as FinalExam
From Table1 t1, Table2 t2

Is there a way to do this more efficiently/succinctly using an inner join?


回答1:


What you do is a cartesian product which will have n*n rows.

Try this

Select
    student,
    course,
    Exam1,
    Exam2,
    Exam3,
    FinalExam,
From Table1 t1, Table2 t2
Where t1.student=t2.student
and t1.course=t2.course;

This query works on the arrumption that the students have appeared for the either exams 1 or 2 atleast AND either exams 3 or Final. If there is a possible case of absent, then you need to use outer join. Like the following example, but not limited to

Select
    student,
    course,
    Exam1,
    Exam2,
    Exam3,
    FinalExam,
From Table1 t1, Table2 t2
Where t1.student=t2.student(+)
and t1.course=t2.course(+);



回答2:


Here is what I think you want based on some assumptions from your question.

 select isnull(t1.student, t2.student),  isnull(t1.course, t2.course),
    IsNull( t1.Exam1, 0) as Exam1 ,
    IsNull( t1.Exam2, 0) as Exam2,
    IsNull( t2.Exam3, 0) as Exam3,
IsNull( t2.FinalExam, 0) as FinalExam
From Table1 t1 
   full outer join  Table2 t2 
        on t1.student = t2.student 
            and t1.course = t2.course


来源:https://stackoverflow.com/questions/18836382/merge-sql-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!