如何计算Sql中动态数据透视查询的百分比

时间:2014-12-27 16:23:44

标签: sql sql-server sql-server-2012

我希望在学生面前展示每个科目的分数,以及总科目的百分比。

为此目的,我进行动态透视查询,此查询为我提供了所有主题 但实际上我不知道如何计算百分比百分比,因为我的列是动态的

    Declare @cols AS nvarchar(max),
    @query as nvarchar(max)

Select @cols = Stuff(
    (   
     Select distinct ','+ QUOTENAME(SubNameUr) 
     from TblSubject Sub
     Inner join TblSubClassRel subr on Sub.SubId = subr.SubId
     inner join TblClass C on subr.ClassID = C.ClassID
     inner join  TblClassSchedule csh on subr.ClassID = csh.ClassID
     inner join TblSubAss sba on subr.ClassSubRelId = sba.ClassSubRelId
     inner join TblSemAssigning SemA on csh.SemAssId = SemA.SemAssId
     inner join TblAcademicYear Ay on SemA.AcademicYearId = Ay.AcademicYearId 
     Where csh.ClassSchID = 207 and Ay.AcademicYearName ='2008-09'
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

Set @query = ' Select pivot1.FullName,pivot1.ClassName, ' + @cols + ' 

          From
          (
            Select distinct S.First_NameUr  + S.Last_NameUr as FullName,c.ClassName,
            sub.SubNameUr,
            subr.obtainedMarks,sd.StudentDetailId--,(SUM(obtainedMarks)/COUNT(sd.StudentDetailId))as Percentage
            From TblStudentBioData s
            inner join TblStudentDetail sd on s.Student_ID = sd.Student_ID
            inner join TblStudentSubAss ssb on sd.StudentDetailID = ssb.StudentDetailID
            inner join TblClassSchedule csh on sd.ClassSchId = csh.ClassSchID
            inner join TblSubAss sba on ssb.SubAssId = sba.SubAssId 
            inner join TblClass c on csh.ClassID = c.ClassID
            inner join TblSubClassRel sc on sba.ClassSubRelId = sc.ClassSubRelId
            inner join TblSubject sub on sc.SubId = sub.SubId
            inner join TBLSubResult subr on ssb.StudentSubAssID = subr.StudentSubAssID
            where csh.ClassSchID =207
            group by S.First_NameUr,S.Last_NameUr,c.ClassName,sub.SubNameUr,subr.obtainedMarks,sd.studentdetailId
    ) tem   
    pivot
    (
        max(obtainedMarks)
        for SubNameUr in('+@cols+')

    )pivot1 '

上面的查询给了我以下输出

enter image description here

1 个答案:

答案 0 :(得分:1)

你可能想要这样的东西:

SUM(obtainedMarks) OVER(PARTITION BY sd.StudentDetailId) / COUNT(sd.StudentDetailId) OVER(PARTITION BY sd.StudentDetailId) AS Percentage