2012-05-10 76 views
0

這裏有兩個表。如何在MS SQL中使用相同的數據寫兩個MS SQL代碼

Table1 
SchoolID Teacher_name comm_yr 
01   John   1990 
02   Heley   1995 
03   George   1994 
04   Chris   1998 
05   Mary   1993 

Table2 
School_ID Student_name 
01  Heley 
02  Chris 
03  Chris 
04  Mary 
05  Heley 

我想列出每個學生做過的每年學生以及每個學生做過的年份。

SELECT Teacher_name, comm_yr As Teacher_comm_yr, comm_yr As Student_comm_yr 
FROM Table1 INNER JOIN Table2 
WHERE comm_yr (SELECT comm_yr As Teacher_comm_yr From Table1 
Where teacher_name=student_name); 

該表顯示

Teacher_name Teacher_comm_yr Student_comm_yr 
John     1990 1990 
Heley     1995 1995 
George     1994 1994 
Chris     1998 1998 
Mary     1993 1993 

但我要的是

Teacher_name Teacher_comm_yr Student_comm_yr 
John    1990 
Heley    1995  1990 
George    1994  
Chris    1998  1995 
Chris    1998  1994 
Mary    1993  1998 

但我只能執行同年 能否請您幫助..

謝謝!

+0

請提供需要的輸出樣本。 – RedFilter

+0

它有錯誤。我什至不能執行它 – user1355061

+0

他的意思是爲上述兩個基表什麼是你期望看到的輸出..你不必運行查詢..通過鍵入它自己建立它..:/ – Baz1nga

回答

0

一些注意事項。

SELECT 
    t1.Teacher_name, 
    t2.Student_name, 
    t1.comm_yr AS Teacher_comm_yr, 
    t1.comm_yr AS Student_comm_yr 
FROM Table1 AS t1 
LEFT JOIN Table2 AS t2 
ON t2.student_name = t1.teacher_name; 

根據你的數據,我不明白克里斯從哪裏得到了1995年。

因此,如何:

SELECT t.SchoolID, 
     t.Teacher_name, 
     t.comm_yr, 
     q.SchoolID, 
     q.Teacher_name, 
     q.Student_name, 
     q.comm_yr 
FROM table11 t 
     LEFT JOIN (SELECT a.SchoolID, 
         a.Teacher_name, 
         b.Student_name, 
         a.comm_yr 
        FROM table11 AS a 
         INNER JOIN table22 AS b 
          ON a.SchoolID = b.School_ID) AS q 
     ON t.Teacher_name = q.Student_name; 

我已經包含多個字段(列)不是必要的,爲了驗證這一想法。

+0

Chris是來自t1 – user1355061

+0

的Heley下的學生感謝您的幫助 但它顯示的就像第一張桌子。所有這些年都一樣。我想要第二張桌子。 – user1355061

+0

好吧,我想我明白你想要什麼。 – Fionnuala