The users who don’t know much about MySQL; MySQL is an RDMS that uses the SQL language to manage the data of a website. In MySQL to perform addition on the particular groups, we use the SUM() function with the GROUP BY clause. This post helps us to understand the usage of the GROUP BY clause with the SUM() function.
What is a SUM() function
The SUM() function is used to calculate the sum of integer data in the table, for better understanding, let us consider an example:
Customer_name | Customer_books | Total_price($) | Price_of_stationary |
---|---|---|---|
John | Geography | 7 | 3 |
Paul | International law | 23 | 1 |
John | Science | 6 | 12 |
Paul | English | 20 | 4 |
A table has been created in MySQL with the name of Customer_data using the data above, which can be represented by using the command:
If we want to perform addition on the Total_price column, we can do so simply using the SUM() function:
The total sum of the column, Total_price, has been displayed.
How to use SUM() with GROUP BY in MySQL
To perform addition on groups, we use the GROUP BY clause with the SUM(), for example, in the above table, there are only two customers; John and Paul who purchased the books, to have the Total_price of both customers we use the SUM() function with the GROUP BY clause:
In the above output, we can see that the sum of the price of the books purchased by both customers is displayed separately. We can also sum the multiple columns by using the SUM() function with GROUP BY clause:
Conclusion
MySQL is a popular RDBMS to manage data of the relational database, it supports a lot of SQL functions that take one or more inputs and give a single output after performing that specific task. The SUM() is one of the aggregate functions that is used to perform addition on provided data. In this post, we have discussed the usage of the SUM() function and also used it with the GROUP BY clause