简体   繁体   中英

SQL Server complex join

I have 3 tables as shown below

在此处输入图像描述

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. 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?

Sample Data:

在此处输入图像描述

You are joining table C, if no score present the row is discarded.

You should use left join in C as used in D.

Hope it helps!


Also I would put all conditions related to the left join tables in the view and not on the where section.

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)

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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