When we want to perform calculation on any column like Sum or want to use aggregate functions like Min, Max in our Select statement then we use GROUP BY statement. GROUP BY statement returns result across multiple records and group the results by one or more desired columns.
Summery
SELECT col_name1,col_name2, aggregate_fun(col_name)
FROM table_name
WHERE
GROUP BY col_name1
where Col_Name1, Col_Name2…Col_name N are the table columns names.
aggregate_fun can be the functions such as max,count etc.
Example
For Example we have the following Employee records:
Employee Id | EmpName | Age | Department | Salary |
1 | Ankur | 28 | Sales | 2500.00 |
2 | David | 32 | Sales | 3000.00 |
3 | John | 30 | HR | 2200.00 |
4 | James | 45 | Production | 4200.00 |
5 | Mohan | 35 | Production | 4300.00 |
6 | Ram | 40 | HR | 2000.00 |
7 | McDonald | 30 | HR | 2600.00 |
8 | Rohan | 23 | Sales | 1600.00 |
If we want to get the Sum of Salary of each department then we can use the Group By Clause as follows
SELECT Department,Sum([Salary]) as Salary FROM [EmployeeDatabase].[dbo].[tbl_Employee] Group By Department
And you will get the following Result
Department | Salary |
HR | 6800.00 |
Production | 8500.00 |
Sales | 7100.00 |
Group By Clause with more than one column
If we want to get the Sum of Salary of each department group by employee Age then we can use the Group By Clause as follows
SELECT Department,Age,Sum([Salary]) as Salary FROM [EmployeeDatabase].[dbo].[tbl_Employee] Group By Department,Age
And you will get the following Result
Department | Age | Salary |
Sales | 23 | 1600.00 |
Sales | 28 | 2500.00 |
HR | 30 | 4800.00 |
Sales | 32 | 3000.00 |
Production | 35 | 4300.00 |
HR | 40 | 2000.00 |
Production | 45 | 4200.00 |