The challenge is to find the employees with the second highest salary in each department. However, it is a little more complicated because if two employees have the same salary, you need to list both of them.
ROW_NUMBER() and CTE
;WITH T AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary DESC) AS Ord FROM @Employees ) SELECT * FROM T t1 WHERE EXISTS ( SELECT * FROM T t2 WHERE t1.Department = t2.Department AND t2.Ord = 2 AND t1.Salary=t2.Salary )
Tags: