You want to calculate the average salary per department and then find departments with average salary above 5000. Which query correctly uses multiple CTEs to achieve this?
hard📝 Application Q8 of 15
SQL - Common Table Expressions (CTEs)
You want to calculate the average salary per department and then find departments with average salary above 5000. Which query correctly uses multiple CTEs to achieve this?
AWITH dept_avg AS (SELECT dept_id, salary FROM employees GROUP BY dept_id), high_avg AS (SELECT dept_id FROM dept_avg WHERE avg_sal > 5000) SELECT * FROM high_avg;
BWITH dept_avg AS (SELECT dept_id, AVG(salary) AS avg_sal FROM employees), high_avg AS (SELECT dept_id FROM dept_avg WHERE avg_sal > 5000) SELECT * FROM high_avg;
CWITH dept_avg AS (SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id), high_avg AS (SELECT dept_id FROM dept_avg WHERE avg_sal > 5000) SELECT * FROM high_avg;
DWITH dept_avg AS (SELECT dept_id, AVG(salary) AS avg_sal FROM employees GROUP BY dept_id) SELECT * FROM dept_avg WHERE avg_sal > 5000;
Step-by-Step Solution
Solution:
Step 1: Calculate average salary per department
dept_avg CTE correctly groups by dept_id and calculates AVG(salary).
Step 2: Filter departments with avg_sal > 5000
high_avg CTE selects dept_id from dept_avg where avg_sal > 5000.
Step 3: Select from high_avg
The final SELECT returns departments meeting the condition.
Final Answer:
Query with two CTEs: dept_avg and high_avg, filtering avg_sal > 5000 -> Option C
Quick Check:
Multiple CTEs can chain calculations and filters [OK]
Quick Trick:Use one CTE for aggregation, next for filtering [OK]
Common Mistakes:
Omitting GROUP BY in aggregation
Not chaining CTEs properly
Using wrong columns in GROUP BY
Master "Common Table Expressions (CTEs)" in SQL
9 interactive learning modes - each teaches the same concept differently