Use a CTE (WITH clause)
Question
Using a WITH clause, calculate the average salary of each department, then show the department name and its average (rounded) for departments whose average is above 6000.
employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city
Your query
Ctrl+Enter to run
Result
Expected result
| name | avg_salary |
|---|---|
| Engineering | 8225 |
| Sales | 6300 |
Hint
WITH name AS (SELECT ...) creates a named result you can join like a table.
Show the solution
solution.sql
Run this code
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT d.name, ROUND(a.avg_salary) AS avg_salary
FROM dept_avg a
JOIN departments d ON d.id = a.department_id
WHERE a.avg_salary > 6000;
Why it works
The CTE dept_avg is calculated first and then used like a table in the main query. It splits a hard query into two easy steps that you can read from top to bottom.
Common mistake
A CTE only exists for the one statement that follows it. Running SELECT * FROM dept_avg on its own afterwards fails with "no such table".