SQL SUM

Write SQL to use of aggregate sum() function.

The SUM() function calculates the sum of a set of values. Sum() is aggregate function

Example


Table: Employee                             Table: Department
+----+-------+--------+--------------+      +----+----------+
| Id | Name  | Salary | DepartmentId |      | Id | Name     |
+----+-------+--------+--------------+      +----+----------+
1  | Ram   | 85000  | 1            |      | 1  | IT       |
2  | Henry | 80000  | 2            |      | 2  | Sales    |
3  | Sam   | 60000  | 2            |      +----+----------+
4  | Shyam | 60000  | 1            |
5  | Geeta | 90000  | 1            |
6  | Sheet | 90000  | 1            |
7  | Leela | 80000  | 1            |
8  | Geeta | 70000  | 1            |
+----+-------+--------+--------------+

Query: Sum of all employee salary


select sum(Salary) as TotalSalary from employee;

Result:

+-------------+
| TOTALSALARY |
+-------------+
615000      |
+-------------+

Query: Sum of all employee salary of each department wise


SELECT DP.NAME,SALARY FROM (
SELECT SUM(EP.Salary) SALARY,EP.DepartmentID
FROM Employee EP 
GROUP BY EP.DepartmentID) JOIN Department DP
ON DepartmentID=DP.ID

Result:


+-------+----------+
|NAME   |SALARY    |
+-------+----------+
|IT     |475000    |
|Sales  |140000    |
+-------+----------|

No comments:

Post a Comment