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.
Solution to TSQL Beginners Challenge 1
;With CTE (EmployeeID, SalaryRank) AS ( SELECT EmployeeID,RANK() Over (partition by Department ORder by salary Desc) AS SalaryRank From @Employees ) Select E.EmployeeID, E.EmployeeName, E.Department, E.Salary From CTE C Inner Join @Employees E On C.EmployeeID = E.EmployeeID WHERE C.SalaryRank = 2 Order by E.Salary
Tags: