SQL SUM() Function
Submitted by admin on Tuesday, May 3, 2011 - 10:51.
The SUM function is an aggregate function use to calculate the total amount of a column. SUM function can be use only in numeric column.
Syntax
SELECT SUM(column_name) FROM TABLE
Consider the following table for this exercise
Users
| Firstname | Lastname | Salary | DeptID |
|---|---|---|---|
| John | Smith | 1000 | 1 |
| Mathew | Simon | 3000 | 1 |
| Bill | Steve | 2200 | 1 |
| Amanda | Rogers | 1800 | 2 |
| Steve | Hills | 2800 | 2 |
| Steve | jobs | 2400 | 2 |
| bill | cosby | 700 | 3 |
Example # 1
SELECT SUM(Monthly_Salary) AS TotalSalary FROM Users
Result of the Query
| TotalSalary |
|---|
| 13900 |
You can also add other field and using the GROUP BY Clause.
Example # 2
- SELECT DeptID, SUM(Users.Salary) AS TotalSalary
- FROM Users
- GROUP BY DeptID
Result of the Query
| DeptID | TotalSalary |
|---|---|
| 1 | 6200 |
| 2 | 7000 |
| 3 | 700 |
As you can see the Salary is summed up by DeptID.