添加其他数学表达式来聚合函数

时间:2016-11-20 23:18:57

标签: sql

我试图将aggregate function与其他数学函数结合起来,例如:

SELECT student.name, (exam.midterm1 + +exam.midterm2 + SUM(student.grade*class.extracredit) AS FINALSCORE
FROM student, class, exam
WHERE student.name = class.studentname
GROUP BY student.name;

^它不会起作用。将聚合函数与sql中的其他数学函数组合的正确方法是什么?

学生表

NAME                           GRADE
------------------------- ----------
Jason                             44
Edward                            11
David                             95
Sean                              76
Jason                             88
David                             76 

班级表

STUDENTNAME              EXTRACREDIT
------------------------- ----------
Jason                              4
Edward                             2
David                              1
Sean                               4

考试表

STUDENTNAME                 MIDTERM1        MIDTERM2
------------------------- ----------      ----------
Jason                             76             87
Edward                            60             80
David                             97             75
Sean                              82             79

2 个答案:

答案 0 :(得分:1)

仅计算学生表中多个等级的总和,并添加JOIN子句以加入学生,班级和考试表,然后使用简单的表达式对四个数值求和,例如:

SELECT 
    s.name, 
    s.total_grade + class.extracredit + 
       exam.midterm1 + exam.midterm2 as finalscore
FROM
    (select name, sum(grade) as total_grade from student group by name) as s
    INNER JOIN class ON s.name = class.studentname
    INNER JOIN exam on exam.studentname = s.name;

更一般的答案是聚合函数的结果当然可以在表达式中与其他值组合,但根据情况,这些其他值也可能必须是聚合函数的结果,或者可能需要添加更多GROUP BY子句的条件。

答案 1 :(得分:0)

根据您的表格结构,您必须计算sumstudent表之间的class,并将结果与​​exam表一起加入,如下所示。

试试如下。

SELECT 
    sc.Name, 
    (sc.GradeAndExtraCredit + exam.midterm1 + exam.midterm2) as FinalScore
FROM
    (SELECT Name, SUM(grade * extracredit) OVER (PARTITION BY Name) as GradeAndExtraCredit FROM student s INNER JOIN class c ON s.Name = c.StudentName) as sc
    INNER JOIN exam on exam.StudentName = sc.Name