如何为此创建视图?

时间:2011-09-06 04:06:57

标签: sql sql-server tsql

也许这将是一个简单的问题,但我不知道如何简单地实现它。 我有两张下面提到的表格。

表A

ID  Student1 Student2 Student1_Class Student2_Class
1    S0001   S0002      A              A
2    S0001   S0003      B              A

表B

  Class StudentID StudentName
    A     S0001     Jack
    A     S0002     Adam
    A     S0003     Lily
    B     S0001     Simpson

我希望得到类似

的结果
   ID  Student1  Name1  Student2  Name2  Student1_Class Student2_Class
    1    S0001   Jack    S0002   Adam      A              A
    2    S0001   Simpson S0003   Lily      B              A

如何基于这两个表创建视图以获得所需的结果?

2 个答案:

答案 0 :(得分:3)

您只需要加入TableB两次,每个学生一次

CREATE VIEW MyView
AS
 SELECT
   A.ID,
   A.Student1,
   B1.StudentName as Name1,
   A.Student2,
   B2.StudentName as Name2,
   B1.Class as Student1_Class,
   B2.Class as Student2_Class
 from
   TableA as A
   INNER JOIN TableB as B1 on B1.StudentID = A.Student1 and B1.Class = TableA.Student1_Class
   INNER JOIN TableB as B2 on B2.StudentID = A.Student2 and B2.Class = TableA.Student2_Class

答案 1 :(得分:3)

你必须在Class和STudent上加入,因为重复了S0001。

但是,输出错误,因为TableA中ID = 2没有A / S0001匹配来获取“Simpson”。所以假设这是一个拼写错误,在这里你g0

CREATE VIEW MyView
AS
 SELECT
   A.ID,
   A.Student1,
   B1.StudentName as Name1,
   A.Student2,
   B2.StudentName as Name2,
   A.Student1_Class,
   A.Student2_Class
 from
   TableA as A
   INNER JOIN
   TableB as B1 ON A.Student1_Class = B1.Class AND A.StudentID = B1.Student2
   INNER JOIN 
   TableB as B2 ON A.Student2_Class = B2.Class AND A.StudentID = B2.Student1