如何获得数据透视表中列的平均值

时间:2015-01-31 04:57:09

标签: c# sql-server

我刚学会了数据透视表的概念,有人帮我提出了这个代码来创建一个:(我添加了平均代码)

  SELECT  pvt.Fname,
            pvt.Lname,
            pvt.[English], 
            pvt.[Mathematics], 
            pvt.[Geography], 
            pvt.[Literature], 
            pvt.[French],
            TotalScore = ISNULL(pvt.[English], 0) + ISNULL(pvt.[Mathematics], 0) + ISNULL(pvt.[Geography], 0) + ISNULL(pvt.[Literature], 0) + ISNULL(pvt.[French], 0)

            AverageScore=AVG((pvt.[English]) + (pvt.[Mathematics]) + (pvt.[Geography]) +(pvt.[Literature])+(pvt.[French]))

    FROM    (   SELECT  s.SubjectName, er.Result, su.Fname, su.Lname 
                FROM    Subject AS s
                        INNER JOIN ExamResults AS er
                            ON s.SubjectID = er.SubjectID
                        INNER JOIN Exam AS e
                            ON er.ExamID = e.ExamID
                        LEFT JOIN Student AS su
                            ON er.StudentID = su.StudentID
                WHERE   e.Class = @Class
            ) AS e
            PIVOT 
            (   MAX([Result])
                FOR [SubjectName] IN ([English], [Mathematics], [Geography], [Literature], [French])
            ) AS pvt;




 Fname  |   Lname  | English | Mathematics | Geography | Literature | French | TotalScore| AverageScore
     -------+----------+---------+-------------+-----------+------------+--------+-------------
    Earnest |   Baker  |   100   |     35      |      -    |     -      |   75   |     210    
     House  | Richards |    56   |      -      |     35    |     -      |   75   |     166
     Jacob  |    Jake  |    86   |     37      |      -    |     75     |    -   |     198 

四个表及其列如下:

主题表列: SubjectID,SubjectName

学生表列: StudentID,Fname,Lname

考试表栏: ExamID,ExamDate,ExamPeriod,Class

ExamResults专栏: ExamResultID,ExamID,StudentID,SubjectID,Result

问题是,Average列没有返回任何值。我正在使用sql server。请问你能帮我辨别我做错了吗?

1 个答案:

答案 0 :(得分:2)

我建议您在total来源查询中找到average的{​​{1}}和results

Pivot