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.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details