如何使用数据透视表选择数据

时间:2019-04-17 07:18:42

标签: sql .net sql-server

我在两个表中都有学生评分数据,我需要在合并的评分表中显示该数据。预期输出如下

enter image description here

 select * from StudentProgressReports

此表的结果是这个

enter image description here

select * from SchoolSubjects where SchoolClassID=181 and SchoolSectionID=227 and IsDeleted=0 and Status=1

此查询结果是这个

enter image description here

我尝试如下

首先,我编写了一个联接查询,即

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

结果是

enter image description here

之后,我尝试使用数据透视表

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;

结果是这个 enter image description here

但是我的预期输出是 enter image description here

您能帮我完成它吗?

0 个答案:

没有答案