Exercise 1
advancedQuestion
Use a CTE to find employees with above-average salary by department.
Table Schema
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
salary DECIMAL(10,2),
department VARCHAR(50)
);Show Solution
Solution
1WITH dept_avg AS (
2 SELECT department, AVG(salary) AS avg_salary
3 FROM employees
4 GROUP BY department
5)
6SELECT e.name, e.department, e.salary, d.avg_salary
7FROM employees e
8JOIN dept_avg d ON e.department = d.department
9WHERE e.salary > d.avg_salary;Expected Output
| name | department | salary | avg_salary | |---|---|---|---| | Alice | Engineering | 80000 | 70000 |
Explanation
CTEs (Common Table Expressions) make complex queries more readable by breaking them into named steps.