【发布时间】:2015-01-31 04:57:09
【问题描述】:
我刚刚学习了数据透视表的概念,有人帮我想出了这个代码来创建一个:(我添加了平均代码)
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 服务器。请你能帮我找出我做错了什么吗?
【问题讨论】:
-
能否添加示例数据和预期输出
-
尝试 /5 而不是 AVG
-
表格在这里。 stackoverflow.com/questions/28233022/…@NoDisplayName
-
在平均函数中总结主题时使用“ISNULL”以避免任何总结错误。并按照 SARATH 所说的那样得到平均值,除以科目总数。
-
@SarathAvanavu - 干得好。连OP都懒得回复
标签: c# sql-server