Junior
Detailed answer
GROUP BY & Window
SQL & Databases
Write a query for the highest salary per department.
Short answer: GROUP BY DepartmentId with MAX(Salary), or use RANK/DENSE_RANK PARTITION BY DepartmentId to also return employee names tied for max.
Sample solution
T-SQL
-- Aggregate only
SELECT DepartmentId, MAX(Salary) AS MaxSalary
FROM Employees
GROUP BY DepartmentId;
-- Employees earning the max in their department
SELECT EmpId, Name, DepartmentId, Salary
FROM (
SELECT *, DENSE_RANK() OVER (
PARTITION BY DepartmentId ORDER BY Salary DESC
) AS rnk
FROM Employees
) t
WHERE rnk = 1;
If they want names, window functions beat a join-back to MAX aggregates.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png