我的问题还有其他解决方案吗?

时间:2019-04-03 15:47:47

标签: sql-server

对于给定的输入,我需要获得所需的输出

输入

Room

输出

Firebase

我以一种方式得到解决方案

table1                                   
+----------------------+
id      |    coursename   
+-----------------------+      
1            SQL
2            Artificial Intelligence
3            Machine Learning

table2

+---------------------------+
id       |    teachername
+----------------------------+
1             shreya
1             ramya
2             darshan
2             ravi

table3

+----------------------------+
id        |   studentname
+-----------------------------+
1               raj
1              mani
1              chandru
2              prem

2 个答案:

答案 0 :(得分:0)

您希望LEFT JOINFULL OUTER JOIN一起使用:

WITH cte AS (
     SELECT t1.id, t1.coursename, t2.teachername,
            ROW_NUMBER() OVER (PARTITION BY t1.id ORDER BY(SELECT 1)) AS RN
     FROM table1 t1 LEFT JOIN
          table2 t2
          ON t2.id = t1.id

), cte1 AS (
     SELECT t1.id, t1.coursename, t3.studentname,
            ROW_NUMBER() OVER (PARTITION BY t1.id ORDER BY(SELECT 1)) AS RN
     FROM table1 t1 LEFT JOIN
          table3 t3
          ON t3.id = t1.id
)

SELECT ISNULL(c.id, c1.id) AS id, ISNULL(c.coursename, c1.coursename) AS coursename, c.teachername, c1.studentname
FROM cte c full outer join
     cte1 c1 
     ON c1.id = c.id and c1.RN = c.RN;

答案 1 :(得分:0)

您需要在学生表中有老师ID,在教师表中有老师ID:

DECLARE @course TABLE
(
    Id int,
    CourseName varchar(100)
)

DECLARE @teacher TABLE
(
    CId int,
    TId int,
    TeacherName varchar(100)
)

DECLARE @student TABLE
(
    Id int,
    TId int,
    StudentName varchar(100)
)

INSERT INTO @course VALUES(1,'SQL')
INSERT INTO @course VALUES(2,'AI')
INSERT INTO @course VALUES(3,'ML')

INSERT INTO @teacher VALUES(1, 1,'shreya')
INSERT INTO @teacher VALUES(1, 2, 'ramya')
INSERT INTO @teacher VALUES(2, 3, 'darshan')
INSERT INTO @teacher VALUES(2, 4, 'ravi')

INSERT INTO @student VALUES(1,1,'raj')
INSERT INTO @student VALUES(1,1,'mani')
INSERT INTO @student VALUES(1,2,'chandra')
INSERT INTO @student VALUES(2,3,'prem')


SELECT c.Id, c.CourseName, t.TeacherName, s.StudentName 
FROM @course c  
    LEFT JOIN @teacher t ON c.Id = t.CId 
    LEFT JOIN @student s ON c.Id = s.Id AND t.TId = s.TId

输出:

enter image description here