Web Info and IT Lessons Blog...

Saturday, 29 November 2014

MySql Sum

The previous lesson of MySql Lessons Series was about MySql Group By and Order By and in this lesson we will learn about Sum in MySql.

MySql SUM Function

MySql SUM()

MySql SUM function is used to sum the records of a specific column or columns of a table. The basic structure of MySql Sum function is given below:



SELECT SUM(ColumnName) as AliasName 
FROM TableName WHERE 1


Consider the user table shown in the image below:

Sum Table

The above table shows personal details of the users and balance payable to them. If we want to know the total balance payable to all the users, all we need to do is sum the balance of all users using MySql Sum function. MySql Sum query to add the balance of all users in the user table is given below:



SELECT SUM(balance) as total_balance FROM user WHERE 1


The above query will return a single result showing the total balance payable to all users.

MySql Sum with Group By

If we want to show the data in the user table in the form of balance payable to the users of each city of a country, we will have to use mysql sum function with group by i.e



SELECT City,SUM(balance) as total_balance FROM user
 WHERE 1 GROUP BY City


The result of above query is shown in the image below:

Mysql Sum and Group By

The above image shows the city names and total balance payable to the users of that city.

No comments:

Post a Comment