У меня есть данные оценок учащихся в двух таблицах, мне нужно отобразить эти данные в сводной таблице оценок. ожидаемый результат следующим образом

select * from StudentProgressReports
этот результат таблицы это

select * from SchoolSubjects where SchoolClassID=181 and SchoolSectionID=227 and IsDeleted=0 and Status=1
результат запроса следующий

Я пытался следующим образом
сначала я написал один запрос на соединение, т. Е.
select spr.StudentID,ss.FirstName,ss.LastName,spr.SchoolSubID,sb.SubjectName,spr.Marks,spr.TotalMarks,spr.Grades from StudentProgressReports spr with(nolock)
left outer join SchoolStudents ss with(nolock) on spr.StudentID=ss.StudentId
left outer join SchoolSubjects sb with(nolock) on spr.SchoolSubID=sb.SchoolSubID
where spr.IsDeleted=0
and spr.ACID is not null
and spr.ExamID=42
and sb.SchoolClassID=181
and sb.SchoolSectionID=227
and sb.IsDeleted=0
and sb.Status=1
go
результат таков
после этого попробовал с сводной таблицей
DECLARE @columns AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @columns = STUFF((SELECT distinct ',' + ISNULL(QUOTENAME(sub.subjectname),'NA')
FROM SchoolSubjects sub where len(sub.subjectname)>0 and SchoolClassID=181 and SchoolSectionID=227
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
print @columns
set @query = 'SELECT FirstName,LastName,' + @columns + ',Marks,TotalMarks,Grades from
(
select spr.StudentID,ss.FirstName,ss.LastName,spr.SchoolSubID,sb.SubjectName,spr.Marks,spr.TotalMarks,spr.Marks as m1,spr.Grades from StudentProgressReports spr with(nolock)
left outer join SchoolStudents ss with(nolock) on spr.StudentID=ss.StudentId
left outer join SchoolSubjects sb with(nolock) on spr.SchoolSubID=sb.SchoolSubID
where spr.IsDeleted=0
and spr.ACID is not null
and spr.ExamID=42
and sb.SchoolClassID=181
and sb.SchoolSectionID=227
and sb.IsDeleted=0
and sb.Status=1
) Tab1
pivot
(
sum(m1) FOR SubjectName IN (' + @columns + ')
) AS Tab2 '
PRINT @query;
EXEC sp_executesql @query;
результат такой

но мой ожидаемый результат

Не могли бы вы помочь мне сделать это.