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 DepartmentMaxSalaries as ( select Department, MAX(Salary) as MaxSalary from Employees group by Department ), SecondSalaries as ( select Department, MAX(Salary) as SecondMaxSalary from Employees as s where Salary != (select MaxSalary from DepartmentMaxSalaries as d where d.Department = s.Department) group by Department ) select * from Employees where Salary = (select SecondMaxSalary from SecondSalaries where SecondSalaries .Department = Employees.Department) order by Department, EmployeeID
Tags: