SQL Server复杂连接

问题描述 投票:0回答:1

我有3张桌子,如下所示

enter image description here

我已经编写了一个SQL脚本,以按分数返回特定术语和班级中的所有学生科目,无论是否记录分数。但是以下脚本仅返回每个主题的记录分数。

select 
    a.StudentId, b.SubjectId, c.Score as tCA, d.Score as tExam 
from 
    tbl_StudentToClass a
join 
    tbl_SubjectToClass b on a.ClassId = b.ClassId
join 
    (select 
         sum(Score) AS Score, SubjectId, StudentId, TermId 
     from 
         tbl_Score 
     where 
         ScoreType = 1 
     group by 
         SubjectId, StudentId, TermId) c on b.SubjectId = c.SubjectId
     join 
    (select 
         sum(Score) AS Score, SubjectId, StudentId, TermId 
     from 
         tbl_Score 
     where 
         ScoreType = 2 
     group by 
         SubjectId, StudentId, TermId) d on b.SubjectId = d.SubjectId
where 
    a.ClassId = 2 and
    a.SchoolSessionId = 5 and 
    c.StudentId = a.StudentId and 
    c.TermId = 8 and
    d.StudentId = a.StudentId and 
    d.TermId = 8

我如何返回所选班级的所有科目,无论是否有分数?

样本数据:

enter image description here

sql sql-server join
1个回答
0
投票

您正在加入表C,如果没有得分,则该行将被丢弃。

您应该像在D中一样在C中使用左连接。

希望有帮助!


此外,我会将与左连接表相关的所有条件放在视图中,而不是在where部分中。

尝试此版本,并告诉我现在是否它返回了所有所需的记录(对不起,我现在没有活动的SQL Server,并且我无法对其进行测试)

select 
    a.StudentId, b.SubjectId, c.Score as tCA, d.Score as t 
from 
    tbl_StudentToClass a
join 
    tbl_SubjectToClassArm b on a.ClassToClassArmId = b.ClassToClassArmId
left join 
    (select 
         sum(Score) AS Score, SubjectId, StudentId, TermId 
     from 
         tbl_Score 
     where 
         ScoreType = 1 and TermId = 1100
     group by 
         SubjectId, StudentId, TermId) c on b.SubjectId = c.SubjectId
left join 
    (select 
         sum(Score) AS Score, SubjectId, StudentId, TermId 
     from 
         tbl_Score 
     where 
         ScoreType = 2 and TermId = 1100
     group by 
         SubjectId, StudentId, TermId) d on b.SubjectId = d.SubjectId
where 
    a.ClassToClassArmId = 135 and
    a.SchoolSessionId = 1069 and 
    c.StudentId = a.StudentId and 
    d.StudentId = a.StudentId 
热门问题
推荐问题
最新问题