Mid
Window Functions
SQL & Databases
How do you find the nth row per group without APPLY?
Short answer: ROW_NUMBER() OVER (PARTITION BY group ORDER BY ...) then filter rn = n in an outer query.
Sample solution
T-SQL
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (
PARTITION BY DepartmentId ORDER BY Salary DESC
) AS rn
FROM Employees
) t
WHERE rn = 2;
This pattern replaces many correlated TOP 1 subqueries.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png