Creating my own test tables:
DECLARE @Employee TABLE (Employee_id INT, Name VARCHAR(MAX), Chief_id INT)
DECLARE @Department TABLE (Department_Id INT, Name VARCHAR(MAX))
DECLARE @Emp_Dep TABLE (Employee_id INT, Department_Id INT)
DECLARE @Emp_Sal TABLE (Employee_id INT, Salary DECIMAL)
INSERT INTO @Employee
SELECT 1, 'John Doe', 0 UNION ALL
SELECT 2, 'John Doe', 0 UNION ALL
SELECT 3, 'John Doe', 0 UNION ALL
SELECT 4, 'John Doe', 0 UNION ALL
SELECT 5, 'John Doe', 0 UNION ALL
SELECT 6, 'John Doe', 0 UNION ALL
SELECT 7, 'John Doe', 0;
INSERT INTO @Department
SELECT 1, 'Moomin' UNION ALL
SELECT 2, 'Moo' UNION ALL
SELECT 3, 'Min';
INSERT INTO @Emp_Dep
SELECT 1, 1 UNION ALL
SELECT 2, 1 UNION ALL
SELECT 3, 2 UNION ALL
SELECT 4, 2 UNION ALL
SELECT 5, 3 UNION ALL
SELECT 6, 3 UNION ALL
SELECT 7, 3;
INSERT INTO @Emp_Sal
SELECT 1, 1200 UNION ALL
SELECT 2, 1100 UNION ALL
SELECT 3, 2000 UNION ALL
SELECT 4, 2000 UNION ALL
SELECT 5, 3451 UNION ALL
SELECT 6, 3321 UNION ALL
SELECT 7, 3123;
This version will all people in a department if they are tied :)
WITH [Merged] AS (
SELECT [@Employee].[Employee_id],
[@Employee].[Name],
[@Department].[Name] [Department],
[@Department].[Department_Id],
[@Emp_Sal].[Salary]
FROM @Employee
INNER JOIN @Emp_Sal ON [@Employee].[Employee_id] = [@Emp_Sal].[Employee_id]
INNER JOIN @Emp_Dep ON [@Emp_Sal].[Employee_id] = [@Emp_Dep].[Employee_id]
INNER JOIN @Department ON [@Emp_Dep].[Department_Id] = [@Department].[Department_Id]
)
SELECT [Main].Employee_id, [Main].Name, [Main].Department, [Main].Salary
FROM Merged [Main]
WHERE [Salary] = (SELECT MAX(Salary) FROM [Merged] WHERE Department_Id = [Main].Department_Id);
Whereas this version will only select 1 from each department, you'll have to figure out a way to get the person you want on top in the ROW_NUMBER() OVER
WITH [Merged] AS (
SELECT [@Employee].[Employee_id],
[@Employee].[Name],
[@Department].[Name] [Department],
[@Department].[Department_Id],
[@Emp_Sal].[Salary],
ROW_NUMBER() OVER(ORDER BY [@Department].[Department_Id] ASC, [@Emp_Sal].[Salary] DESC, [@Employee].[Employee_id] ASC) AS 'RowNumber'
FROM @Employee
INNER JOIN @Emp_Sal ON [@Employee].[Employee_id] = [@Emp_Sal].[Employee_id]
INNER JOIN @Emp_Dep ON [@Emp_Sal].[Employee_id] = [@Emp_Dep].[Employee_id]
INNER JOIN @Department ON [@Emp_Dep].[Department_Id] = [@Department].[Department_Id]
)
SELECT [Main].Employee_id, [Main].Name, [Main].Department, [Main].Salary
FROM Merged [Main]
WHERE [RowNumber] = (SELECT MAX(RowNumber) FROM [Merged] WHERE Department_Id = [Main].Department_Id);
Worth mentioning might be that it's for Microsoft SQL Server!