Sum of values of columns in MySQL table with GROUP BY , IN and CASE
plus2net plus2net
5.33K subscribers
16,894 views
112

 Published On Sep 6, 2020

https://www.plus2net.com/sql_tutorial...

https://www.plus2net.com/sql_tutorial...

We can get sum of all values of a particular column by using SQL
SELECT SUM(mark) FROM student
Adding Where condition
SELECT SUM(mark) FROM student where id less than equal to 6
Using GROUP BY
We can get the sum of all marks of different classes by using GROUP BY command.
SELECT class, SUM(mark) as total_mark FROM student GROUP BY class

Adding marks of some rows with ID value
Let us add the ID values of first 4 rows .
SELECT SUM(mark) FROM student WHERE id in (1,2,3,4)
We can get total profit by subtracting sell price with buy price.
Sum across multiple columns
We modified our student table and added three more columns showing us the mark obtained by each student in three subjects i.e social, science and math. The new name of student table is student_sum. You can download the SQL dump of this table from the site.
We will display the total mark of three columns
SELECT id, name, class, (social + science + math ) AS total FROM student_sum
Percentage of mark using total mark
By using total mark we can display percentage mark of the student.
SELECT id, name, class, (social + math + science) as total , (( social + science + math)/(95*3) * 100 ) AS percentage FROM student_sum
We can restrict the decimal places of percentage value by using format function.
SELECT id, name, class, (social + math + science) as total, Format((( social + science + math)/(95*3) * 100 ),2) AS percentage FROM student_sum

SUM with GROUP BY
We also use SUM with GROUP BY to get sum of three mark columns of each student
SELECT id, name, class, social, math, science, SUM (social + math + science) as Total FROM student_sum GROUP BY id
As we have total mark of each student , we can use this total mark to assign GRADE value to each student. Here we have used CASE WHEN query to use total mark and then assigned GRADE.

When total mark is more than or equal to 225 then A grade. Total mark is more than or equal to 200 then B grade, C grade when mark is more than 170. If the mark is less than 170 then grade is equal to FAIL.
SELECT id,name,class, social, math, science,
sum(social + math + science ) as Total ,
CASE WHEN sum(social + math + science ) greater than = 225 THEN 'A'
WHEN sum(social + math + science ) greater than =200 THEN 'B'
WHEN sum(social + math + science ) greater than=170 THEN 'C'
ELSE 'FAIL'
END AS grade
from student_sum GROUP BY id

show more

Share/Embed