SQL PHP HTML ASP JavaScript articles and free scripts to download
 

SUM of Multiple columns of MySQL table

We have seen how the sum function is used to get the total value of a column in a mysql table. Now we will learn how to get the query for sum in multiple columns and for each record of a table. For a better understanding we will change our student table a bit by adding marks in different subjects for each record. Now the table will be like this.
idnameclasssocialsciencemath
2Max RuinThree855685
3ArnoldThree554075
4Krish StarFour605070
5John MikeFour608090
6Alex JohnFour559080
7My John RobFifth786070
8AsruidFive858090
9Tes QrySix786070
10Big JohnFour554055
Related Tutorial
MySQL SUM
MySQL Max
MySQL Min
MySQL Avg
We will write a query to display sum of all marks of each student. Note that here we will not use sum sql function inside our query. Here is the code.

SELECT name, ( social + science + math) AS total FROM `student3`

nametotal
Max Ruin 226
Arnold 170
Krish Star 180
John Mike 230
Alex John 225
My John Rob 208
Asruid 255
Tes Qry 208
Big John 150

Multiple columns SUM

As you can see the above sum is sum of marks of each student. This is horizontal sum in our table. Now we will try to get sum of marks of all students in all subjects. So the sum is to be collected in all three columns.

SElECT sum(social + math + science ) as total from student3

total
1852
We can add various other sql commands like where clause etc.

Calculating Percentage of Marks

Let us assume the full mark in each subject is 95. So to get the percentage mark of each student we have to multiply 95 with 3 ( for three subjects ) and then divide that from the total and multiply with 100 here is the query.

SELECT name, (( social + science + math)/(95*3) * 100) AS percentage FROM `student3`

Displaying Total Mark with Percentage

Both total mark and percentage we can display like this

SELECT name, ( social + science + math) as Total,(( social + science + math)/(95*3) * 100) AS percentage FROM `student3`

The Output is here.
nameTotalpercentage
Max Ruin22679.2982
Arnold17059.6491
Krish Star18063.1579
John Mike230 80.7018
Alex John225 78.9474
My John Rob 208 72.9825
Asruid255 89.4737
Tes Qry 208 72.9825
Big John 150 52.6316
Download the SQL dump of the above student table


aqlan19-07-2010
How to calculate Total Mark diffrent between Max Ruin and Arnold?
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked


Join Our Email List
Email:  
For Email Newsletters you can trust
SQL Tutorial List
MySQL Math
SQL Commands
SQL Sections
Date & Time
Join Table
String
Math