Complete the code to select the first salary value in each department.
SELECT department_id, [1](salary) OVER (PARTITION BY department_id ORDER BY salary) AS first_salary FROM employees;The FIRST_VALUE function returns the first value in the ordered partition, which here is the lowest salary per department.
Complete the code to select the last salary value in each department.
SELECT department_id, [1](salary) OVER (PARTITION BY department_id ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_salary FROM employees;The LAST_VALUE function returns the last value in the ordered partition. The frame clause ensures it looks at the entire partition.
Fix the error in the code to correctly get the last salary per department.
SELECT department_id, LAST_VALUE(salary) OVER (PARTITION BY department_id ORDER BY salary [1]) AS last_salary FROM employees;To get the correct last value over the entire partition, the frame must be set to ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. Otherwise, LAST_VALUE returns the current row's value.
Fill both blanks to select the first and last hire dates per department.
SELECT department_id, [1](hire_date) OVER (PARTITION BY department_id ORDER BY hire_date) AS first_hire, [2](hire_date) OVER (PARTITION BY department_id ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_hire FROM employees;
FIRST_VALUE gets the earliest hire date per department, and LAST_VALUE gets the latest hire date with the correct frame clause.
Fill all three blanks to create a query that shows employee name, first salary, last salary, and the difference between them per department.
SELECT employee_name, department_id, [1](salary) OVER (PARTITION BY department_id ORDER BY salary) AS first_salary, [2](salary) OVER (PARTITION BY department_id ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_salary, [3] - [2] AS salary_diff FROM employees;
The query uses FIRST_VALUE and LAST_VALUE to get the first and last salaries per department. The difference is calculated by subtracting the last salary from the current salary.