SQL Group by Clause

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.
is the condition on the basis query select the records.
aggregate_fun can be the functions such as max,count etc.
 

Example

For Example we have the following Employee records:
 

Employee IdEmpNameAgeDepartmentSalary
1Ankur28Sales2500.00
2David32Sales3000.00
3John30HR2200.00
4James45Production4200.00
5Mohan35Production4300.00
6Ram40HR2000.00
7McDonald30HR2600.00
8Rohan23Sales1600.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

 

DepartmentSalary
HR6800.00
Production8500.00
Sales7100.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
 

DepartmentAgeSalary
Sales231600.00
Sales282500.00
HR304800.00
Sales323000.00
Production354300.00
HR402000.00
Production454200.00

 

Author: Ankur

Have worked primarily in the domain of Calling, CRM and direct advertisers services. My technological forte is Microsoft Technologies especially Dot Net (Visual Studio 2003, 2005, 2008, 2010 and 2012) and Microsoft SQL Server 2000,2005 and 2008 R2. My Area of Expertise is in C#. Net, VB.Net, MS-SQL Server, ASP. Net, Silverlight, HTML, XML, Crystal Report, Active Reports, Infragistics, Component Art, ComponeOne, Lead Tools etc.