- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select and sum with grouping in MySQL?
To sum, use the aggregate function SUM(). With that, group using MySQL GROUP BY. Let us first create a table −
mysql> create table DemoTable -> ( -> ProductName varchar(20), -> ProductQuantity int, -> ProductPrice int -> ); Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Product-1',2,50); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Product-2',3,80); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Product-2',4,100); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Product-1',4,150); Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output−
+-------------+-----------------+--------------+ | ProductName | ProductQuantity | ProductPrice | +-------------+-----------------+--------------+ | Product-1 | 2 | 50 | | Product-2 | 3 | 80 | | Product-2 | 4 | 100 | | Product-1 | 4 | 150 | +-------------+-----------------+--------------+ 4 rows in set (0.00 sec)
Following is the query to select with grouping in MySQL −
mysql> select *,sum(ProductQuantity*ProductPrice) as Total from DemoTable -> group by ProductName;
This will produce the following output−
+-------------+-----------------+--------------+-------+ | ProductName | ProductQuantity | ProductPrice | Total | +-------------+-----------------+--------------+-------+ | Product-1 | 2 | 50 | 700 | | Product-2 | 3 | 80 | 640 | +-------------+-----------------+--------------+-------+ 2 rows in set (0.00 sec)
Advertisements