How to write ms sql code for two column with same datas in MS SQL

霸气de小男生 提交于 2019-12-12 04:10:11

问题


Here it two table.

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

I would like to list the year each student has done as student and the year each student has done as teacher.

    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);

The Table is showing

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

But What I want is

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

But I could only execute the same year Can you please help..

Thanks!


回答1:


Some notes.

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;

I do not understand where Chris got 1995 from, based on your data.

So how about:

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; 

I have included more fields (columns) than necessary, to test the idea.



来源:https://stackoverflow.com/questions/10538447/how-to-write-ms-sql-code-for-two-column-with-same-datas-in-ms-sql

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