How to use ROW_NUMBER() In SQL
This method uses the ROW_NUMBER()
window function to assign a unique row number to each row in the EmployeeReviews
table, partitioned by EmployeeID
and ordered by ReviewDate
.
The main query then filters the results to include only rows where the row number is 1, effectively selecting the first row for each employee.
WITH RankedReviews AS (
SELECT
r.EmployeeID,
r.ReviewDate,
r.Rating,
ROW_NUMBER() OVER (PARTITION BY r.EmployeeID ORDER BY r.ReviewDate) AS RowNum
FROM
EmployeeReviews r
)
SELECT
e.EmployeeID,
e.Name,
e.Salary,
rr.ReviewDate,
rr.Rating
FROM
Employee e
LEFT JOIN RankedReviews rr ON e.EmployeeID = rr.EmployeeID AND rr.RowNum = 1;
Output:
Explanation:
- The
ROW_NUMBER()
function assigns a unique row number to each row in theEmployeeReviews
table, partitioned byEmployeeID
and ordered byReviewDate
. This ensures that the first row for each employee is assigned a row number of 1. - The main query then left joins the
Employee
table with theRankedReviews
common table expression (CTE) onEmployeeID
andRowNum = 1
. This ensures that only the first row for each employee is included in the result.
How to Join to First Row in SQL Server
Joining the first row in SQL Server can be a common requirement in various scenarios, such as when we need to retrieve specific data associated with the first occurrence of a particular group or when you want to fetch additional details related to the first record in a result set.
In this article, We will learn about How to Join to first row in SQL Server by understanding various approaches along with the examples and so on.