MySQL_GroupBy_Having_Practice
MySQL_GroupBy_Having_Practice
Introduction
This document provides a structured set of MySQL queries based on the 'employees' table, focusing
on GROUP BY and HAVING clauses. The questions are categorized into Basic, Intermediate, and
Advanced levels, each with detailed SQL solutions.
Q4. Find the total number of employees in each office, but only include offices with more
than 5 employees.
SQL Query:
SELECT officeCode, COUNT(*) AS employee_count FROM employees GROUP BY officeCode
HAVING COUNT(*) > 5;
Q7. List offices where the number of employees is above the average number of employees
per office.
SQL Query:
SELECT officeCode, COUNT(*) AS employee_count FROM employees GROUP BY officeCode
HAVING COUNT(*) > (SELECT AVG(emp_count) FROM (SELECT COUNT(*) AS emp_count
FROM employees GROUP BY officeCode) AS avg_table);
Q8. Find the number of employees for each unique combination of job title and office code.
SQL Query:
SELECT jobTitle, officeCode, COUNT(*) FROM employees GROUP BY jobTitle, officeCode
ORDER BY officeCode;
Q10. Retrieve employees who have an extension starting with 'x1' and ending with '5'.
SQL Query:
SELECT * FROM employees WHERE extension LIKE 'x1%5';