Bird
0
0

You need to display each employee's salary alongside the average salary of their department, preserving all individual salary rows. Which SQL query accomplishes this?

hard📝 Application Q8 of 15
SQL - Window Functions Fundamentals
You need to display each employee's salary alongside the average salary of their department, preserving all individual salary rows. Which SQL query accomplishes this?
ASELECT employee_id, salary, AVG(salary) FROM employees GROUP BY department_id;
BSELECT employee_id, salary, AVG(salary) OVER (PARTITION BY department_id) AS dept_avg FROM employees;
CSELECT employee_id, salary, AVG(salary) FROM employees GROUP BY employee_id, department_id;
DSELECT employee_id, salary, AVG(salary) FROM employees;
Step-by-Step Solution
Solution:
  1. Step 1: Identify requirement

    Show each employee's salary and the department average without collapsing rows.
  2. Step 2: Analyze options

    SELECT employee_id, salary, AVG(salary) OVER (PARTITION BY department_id) AS dept_avg FROM employees; uses a window function with PARTITION BY department_id, preserving all rows and adding the average per department.
  3. Step 3: Why others are wrong

    Options B and C use GROUP BY, which aggregates rows and loses individual salaries. SELECT employee_id, salary, AVG(salary) FROM employees; lacks grouping or window function.
  4. Final Answer:

    SELECT employee_id, salary, AVG(salary) OVER (PARTITION BY department_id) AS dept_avg FROM employees; meets the requirement.
  5. Quick Check:

    Window functions preserve rows; GROUP BY aggregates. [OK]
Quick Trick: Use window functions to keep rows and add aggregates. [OK]
Common Mistakes:
  • Using GROUP BY and losing individual rows.
  • Not partitioning window function by department.
  • Omitting window function syntax.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes