MySQL Sum() multiple columns

前端 未结 7 850
情话喂你
情话喂你 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:56
    SELECT student, (SUM(mark1)+SUM(mark2)+SUM(mark3)....+SUM(markn)) AS Total
     FROM your_table
     GROUP BY student
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-05 02:03

    Another way of doing this is by generating the select query. Play with this fiddle.

    SELECT CONCAT('SELECT ', group_concat(`COLUMN_NAME` SEPARATOR '+'), ' FROM scorecard') 
    FROM  `INFORMATION_SCHEMA`.`COLUMNS` 
    WHERE `TABLE_SCHEMA` = (select database()) 
    AND   `TABLE_NAME`   = 'scorecard'
    AND   `COLUMN_NAME` LIKE 'mark%';
    

    The query above will generate another query that will do the selecting for you.

    1. Run the above query.
    2. Get the result and run that resulting query.

    Sample result:

    SELECT mark1+mark2+mark3 FROM scorecard
    

    You won't have to manually add all the columns anymore.

    0 讨论(0)
  • 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`
    
    0 讨论(0)
  • 2020-12-05 02:14

    SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table

    0 讨论(0)
  • 2020-12-05 02:17

    You could change the database structure such that all subject rows become a column variable (like spreadsheet). This makes such analysis much easier

    0 讨论(0)
提交回复
热议问题