You want to find each employee's salary difference compared to the previous employee in the same department ordered by salary descending. Which query correctly uses window functions to achieve this?
hard📝 Application Q15 of 15
PostgreSQL - Window Functions in PostgreSQL
You want to find each employee's salary difference compared to the previous employee in the same department ordered by salary descending. Which query correctly uses window functions to achieve this?
ASELECT employee_id, department, salary, salary - LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS salary_diff FROM employees;
BSELECT employee_id, department, salary, salary - LEAD(salary) OVER (ORDER BY salary) AS salary_diff FROM employees;
CSELECT employee_id, department, salary, salary - LAG(salary) FROM employees GROUP BY department ORDER BY salary DESC;
DSELECT employee_id, department, salary, salary - FIRST_VALUE(salary) OVER (PARTITION BY department) AS salary_diff FROM employees;
Step-by-Step Solution
Solution:
Step 1: Use LAG() to get previous row's salary per department
LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) gets previous salary in descending order within department.
Step 2: Subtract previous salary from current salary
salary - LAG(salary) calculates difference compared to previous employee.
Final Answer:
SELECT employee_id, department, salary, salary - LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS salary_diff FROM employees; -> Option A
Quick Check:
LAG() gets previous row value for difference [OK]
Quick Trick:Use LAG() with PARTITION BY and ORDER BY for previous row values [OK]
Common Mistakes:
Using LEAD() instead of LAG() for previous row
Omitting PARTITION BY causing wrong grouping
Trying to use aggregate functions without OVER()
Master "Window Functions in PostgreSQL" in PostgreSQL
9 interactive learning modes - each teaches the same concept differently