MySQL Sum() multiple columns

前端 未结 7 872
情话喂你
情话喂你 2020-12-05 01:16

I have a table of student scorecard. here is the table,

subject  | mark1 | mark2 | mark3 |......|markn
stud1    | 99    | 87    | 92    |      | 46
stud2            


        
7条回答
  •  死守一世寂寞
    2020-12-05 02:07

    If any of your markn columns are "AllowNull" then you will need to do a little extra to insure the correct result is returned, this is because 1 NULL value will result in a NULL total.

    This is what i would consider to be the correct answer.

    SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks` 
    

    IFNULL will return the 2nd parameter if the 1st is NULL. COALESCE could be used but i prefer to only use it if it is required. See What is the difference bewteen ifnull and coalesce in mysql?

    SUM-ing the entire calculation is tidier than SUM-ing each column individually.

    SELECT `student`, SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks` 
    FROM student_scorecard
    GROUP BY `student`
    

提交回复
热议问题