SQL Day 11: Group By in SQL Server
LO1: Grouping rows using Group By
LO2: Filtering Groups
LO3: Difference between Where and Having Clause
Group By clause is used to group a selected set of rows into a set of summary rows by the values of one or more columns or expression. It is always used in conjunction with one or more aggregate functions.
Let’s say we have a table tblEmployee which contains all the salary of employees including the cities.
So if we need to find the maximum salary of employee we can use the MAX(Column_Name) aggregate function to find the highest salary of employees.
select MAX(salary) from tblemployee
In the same way, we can find the minimum salary and total salary of all the employees using different aggregate functions.
select MIN(salary) as [Minimum Salary] from tblemployee
select SUM(salary) as [Total Salary] from tblemployee
Let’s say we have to find out the employee salary as per the different cities, to achieve this we need to use the Group By clause.
select city, SUM(salary) from tblemployee Group By city
If you remove the Group By clause from above statement then SQL will throw an error because in the query we are not grouping the cities so the column we used in a select statement that has to satisfy one or two conditions.
You should either have an aggregate function applied to a column or that column should be the part of Group By clause
Now if we need to breakdown by the employee count also then we need to add the count aggregate function in the select statement.
select city, SUM(salary), COUNT(id) as [Total Employees]
from tblemployee Group By city
Filtering rows using Having Clause
Having clause is used to filter the rows and always place after the Group By clause.
Let’s say we need to filter the tblemployee table as per the gender id so to perform this we need to use Having clause in our query.
select city, SUM(salary), COUNT(id) as [Total Employees]
from tblemployee Group By city, genderid
Having genderid=1
Difference between Where and Having Clause
- Where clause filters the rows before aggregation, whereas Having filter the groups after the aggregations are performed.
- Where clause can be used with SELECT, UPDATE and DELETE statement, whereas Having can only be used with SELECT statement.
- The aggregate function can be used in Having clause whereas aggregate function cannot be used in where clause unless it is in a subquery contained in a Having clause.
That’s all for today. Thank You.
Comments
Post a Comment