Day 17: HAVING Clause
Introduction:
The
HAVINGclause is used to filter groups of rows created by theGROUP BYclause. It is often used with aggregate functions to filter the result set after grouping.
Key Concepts:
Filtering Groups: Apply conditions to groups created by
GROUP BY.Aggregate Functions with HAVING: Use aggregate functions to filter groups.
SQL Commands and Examples:
Using HAVING Clause:
Filter groups based on aggregate function results.
-- Group courses by credits and show only groups with more than 1 course
SELECT Credits, COUNT(*) AS NumberOfCourses
FROM Courses
GROUP BY Credits
HAVING COUNT(*) > 1;
Combining WHERE and HAVING Clauses:
Use the
WHEREclause to filter rows before grouping and theHAVINGclause to filter groups after grouping.
-- Select courses with more than 1 credit and group by credits to show only groups with more than 1 course
SELECT Credits, COUNT(*) AS NumberOfCourses
FROM Courses
WHERE Credits > 1
GROUP BY Credits
HAVING COUNT(*) > 1;
HAVING with Multiple Conditions:
Use multiple conditions in the
HAVINGclause.
-- Group employees by department and show only departments with more than 2 employees and average salary greater than 50000
SELECT Department, COUNT(*) AS NumberOfEmployees, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 2 AND AVG(Salary) > 50000;
Practice Exercise:
Use the Employees table with columns
EmployeeID,FirstName,LastName,Department,Salary.Write a query to group employees by
Departmentand filter groups to show only those with more than 1 employee.Write a query to group employees by
Departmentand filter groups to show only those with an averageSalarygreater than 60000.Write a query to group courses by
Creditsand filter groups to show only those with a totalCreditsgreater than 10.
-- Group employees by department and show only groups with more than 1 employee
SELECT Department, COUNT(*) AS NumberOfEmployees
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 1;
-- Group employees by department and show only groups with an average salary greater than 60000
SELECT Department, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 60000;
-- Group courses by credits and show only groups with a total credits greater than 10
SELECT Credits, SUM(Credits) AS TotalCredits
FROM Courses
GROUP BY Credits
HAVING SUM(Credits) > 10;
Using the HAVING clause effectively allows you to apply conditions to groups, making your data analysis more precise and meaningful.
0 Comments