I have a table of student scorecard. here is the table,
subject | mark1 | mark2 | mark3 |......|markn
stud1 | 99 | 87 | 92 | | 46
stud2 |....................................
.
.
studn |....................................|
Now, I need to sum it for each student of total marks. I got it by using sum(mark1+mark2+...+markn) group by stud
. I want to know how to sum it without adding each column name,it will be huge when in case up to marks26. so could anyone know how to fix it.
7条答案
按热度按时间m0rkklqb1#
eagi6jfj2#
Another way of doing this is by generating the select query. Play with this fiddle.
The query above will generate another query that will do the selecting for you.
Sample result:
You won't have to manually add all the columns anymore.
polkgigr3#
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.
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.
i want to know how to sum it without adding each column name,it will be huge when in case up to marks26
To generate and execute this statement dynamically in sql you would need to use the INFORMATION_SCHEMA.COLUMNS table to create a query string then execute it using a prepared statement saved in a variable.
pepwfjgg4#
SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table
mepcadol5#
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
qkf9rpyu6#
//Mysql sum of multiple rows Hi Here is the simple way to do sum of columns
kkih6yb87#
You could change the database structure such that all subject rows become a column variable (like spreadsheet). This makes such analysis much easier