简体   繁体   English

SQL 服务器复合加入

[英]SQL Server complex join

I have 3 tables as shown below我有 3 个表,如下所示

在此处输入图像描述

I have written a SQL script to return all student subjects in a particular term and class with score whether the score is recorded or not.我编写了一个 SQL 脚本来返回特定学期的所有学生科目和 class 以及分数,无论分数是否被记录。 But the below script return only recorded scores per subject.但是下面的脚本只返回每个科目的记录分数。

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

How do I return all subjects for the selected class whether it has score or not?如何返回所选 class 的所有科目,无论它是否有分数?

Sample Data:样本数据:

在此处输入图像描述

You are joining table C, if no score present the row is discarded.您正在加入表 C,如果不存在分数,则丢弃该行。

You should use left join in C as used in D.您应该在 D 中使用 C 中的左连接。

Hope it helps!希望能帮助到你!


Also I would put all conditions related to the left join tables in the view and not on the where section.此外,我会将与左连接表相关的所有条件放在视图中,而不是放在 where 部分。

Try this version and tell me if now it returns all your desired records (sorry, I have no SQL Server active right now and I cannot test it)试试这个版本,告诉我它现在是否返回所有你想要的记录(对不起,我现在没有 SQL 服务器处于活动状态,我无法测试它)

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM