MySQL query to sum up values of rows and sort the result?



For this, you can use GROUP BY along with ORDER BY clause. Let us first create a table −

mysql> create table DemoTable1499    -> (    -> StudentName varchar(20),    -> StudentMarks int    -> ); Query OK, 0 rows affected (0.46 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1499 values('Chris',56); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1499 values('David',78); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1499 values('Bob',98); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1499 values('Chris',45); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1499 values('David',98); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1499 values('Bob',58); Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

Mysql> select * from DemoTable1499;

This will produce the following output −

+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Chris       |           56 | | David       |           78 | | Bob         |           98 | | Chris       |           45 | | David       |           98 | | Bob         |           58 | +-------------+--------------+ 6 rows in set (0.00 sec)

Following is the query to sum up values of rows and sort the result −

mysql> select StudentName,sum(StudentMarks) as TotalSum from DemoTable1499    -> group by StudentName    -> order by TotalSum desc;

This will produce the following output −

+-------------+----------+ | StudentName | TotalSum | +-------------+----------+ | David       |      176 | | Bob         |      156 | | Chris       |      101 | +-------------+----------+ 3 rows in set (0.00 sec)
Updated on: 2019-12-11T05:46:53+05:30

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements