MySQL Sum() multiple columns

前端 未结 7 866
情话喂你
情话喂你 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 01:58

    The short answer is there's no great way to do this given the design you have. Here's a related question on the topic: Sum values of a single row?

    If you normalized your schema and created a separate table called "Marks" which had a subject_id and a mark column this would allow you to take advantage of the SUM function as intended by a relational model.

    Then your query would be

    SELECT subject, SUM(mark) total 
    FROM Subjects s 
      INNER JOIN Marks m ON m.subject_id = s.id
    GROUP BY s.id
    

提交回复
热议问题