Using FIRST_VALUE and LAST_VALUE to Analyze Salaries
Use FIRST_VALUE and LAST_VALUE Functions
Write a SQL query to find the highest and lowest salaries within each department using FIRST_VALUE and LAST_VALUE.
Solution:
-- Find the highest and lowest salaries within each department.
SELECT DISTINCT
DepartmentID,
FIRST_VALUE(Salary) OVER (PARTITION BY DepartmentID ORDER BY Salary DESC) AS HighestSalary,
LAST_VALUE(Salary) OVER (PARTITION BY DepartmentID ORDER BY Salary ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LowestSalary
FROM Employees;
Explanation:
- The goal is to demonstrate how to use FIRST_VALUE and LAST_VALUE to find the highest and lowest salaries within each department.
- FIRST_VALUE(Salary) : Retrieves the first value in the ordered set (highest salary when ordered descending).
- LAST_VALUE(Salary) : Retrieves the last value in the ordered set (lowest salary when ordered ascending).
- PARTITION BY DepartmentID : Groups data by department.
- ROWS BETWEEN Clause : Ensures LAST_VALUE considers the entire partition.
- These functions simplify retrieving specific values from a window of rows.
- For example, in HR systems, you might use this query to identify salary extremes within departments.
1. Purpose of the Query :
2. Key Components :
3. Why use FIRST_VALUE and LAST_VALUE? :
4. Real-World Application :
Additional Notes:
- The ROWS BETWEEN clause is critical for LAST_VALUE to work correctly.
- Use this exercise to teach how to retrieve specific values from a windowed dataset.
For more Practice: Solve these Related Problems:
- Write a SQL query to find the highest and lowest salaries within each job title using FIRST_VALUE and LAST_VALUE.
- Write a SQL query to retrieve the top-performing employee and the least-performing employee in each team based on sales figures.
- Write a SQL query to analyze the range of salaries (highest minus lowest) within each department.
- Write a SQL query to determine the best and worst scores achieved by students in each subject.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous SQL Exercise: Create a Recursive CTE for Hierarchical Data.
Next SQL Exercise: Parse and Modify JSON Data.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics