MySQL Sum() multiple columns

前端 未结 7 878
情话喂你
情话喂你 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: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.

提交回复
热议问题