
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements