๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ:
You have 2 minutes to solve this SQL query.
Find the departments where the average salary is greater than the company's overall average salary.
๐ ๐ฒ: Challenge accepted! ๐ช
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > (
SELECT AVG(salary)
FROM employees
);
๐ก Explanation:
The query compares each department's average salary with the company's overall average salary.
โข GROUP BY department calculates the average salary for each department.
โข The subquery computes the overall average salary across all employees.
โข HAVING filters only those departments whose average salary exceeds the company average.
This question tests your understanding of:
โ
GROUP BY
โ
HAVING
โ
Aggregate Functions AVG
โ
Subqueries
๐ฏ Expected Output Example
Department: Average Salary
IT: 88,500
Finance: 84,000
HR is excluded because its average salary is below the company average.
๐ Alternative Using a Common Table Expression CTE
WITH company_avg AS (
SELECT AVG(salary) AS avg_salary
FROM employees
)
SELECT
department,
AVG(salary) AS average_salary
FROM employees, company_avg
GROUP BY department, company_avg.avg_salary
HAVING AVG(salary) > company_avg.avg_salary;
Using a CTE can improve readability, especially when the same calculated value is reused in larger queries.
๐ Tip for SQL Job Seekers:
Interviewers often ask questions that compare group-level aggregates with overall aggregates. Master the use of HAVING with subqueriesโitโs a key SQL pattern.
โค๏ธ React with โค๏ธ for more SQL interview challenges!
Post #2915
4.83K
- โค 12