Group by Having Clause
Group by Having Clause
We can use GROUP BY to achieve such results using a single query. GROUP BY groups the data from the
table into different groups based on criteria provided and calculates the aggregate function for each group.
Thus the result has 1 row for each group.
Creating Groups on various
Columns
4
Creating Groups by More Than
One Columns
5
Let us try to write a query to display the department and the total salary paid in each department.
Group By converts the entire rows in a group into a single row in result. You cannot fetch details from
individual rows in a category.
Let us display maximum salary paid to each designation, within each department.
SELECT Dept, Designation, MAX(Salary) FROM Employee GROUP BY Dept, Designation;
You can use multiple aggregate functions in the same query as long as category for
grouping is the same.
SELECT Dept, MIN(SALARY), MAX(Salary) FROM Employee GROUP BY Dept;
Nesting aggregate: SELECT MAX(AVG(Salary)) FROM Employee GROUP BY
dept;
You can use GROUP BY with columns that contain NULL values.
Suppose we want to filter above summarized data. For e.g. if we want to fetch only those departments
whose average salary of their employees is greater than a specific value.
This can be achieved using HAVING clause. Having allows aggregate functions to be used as filter criteria
which cannot be done using WHERE clause.
Let us write a query to display the department and the total salary for those departments
whose total salary is more than 90000.
SELECT DEPT, SUM(Salary) FROM 1. Sort on Grouped Columns
Employee GROUP BY DEPT HAVING 2. For each distinct Grouped Columns
SUM(Salary) > 90000; 3. Calculate aggregate function
4. If aggregate value meets having
condition
5. Add row to result
Rules
14
Q-1) Given the employee table as input, choose the query that displays department wise
average salaries sorted in descending order.
Q-1) Given the employee table as input, choose the query that displays department wise
average salaries sorted in descending order.
Q-2) Given the Employee table as input, which of the following query displays departments that
have more than 1 employees?
Q-2) Given the Employee table as input, which of the following query displays departments that
have more than 1 employees?