I have a table EmpDetails
:
DeptID EmpName Salary Engg Sam 1000 Engg Smith 2000 HR Denis 1500 HR Danny 3000 IT David 2000 IT John 3000
I need to make a query that find the highest salary for each department.
SELECT * FROM department; Get the highest salary of each department on the table. Here our table contains a DEPT_ID and it has two different categories UI DEVELOPERS and BACKEND DEVELOPERS, and we will find out the highest salary of the column.
For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department.
The NTH_VALUE() function explicitly shows you the value of the third-highest salary by department. The ROW_NUMBER() , RANK() , and DENSE_RANK() functions rank the salaries within each department. Then, you can simply find the salary value associated with rank number 3.
SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID
The above query is the accepted answer but it will not work for the following scenario. Let's say we have to find the employees with the highest salary in each department for the below table.
DeptID | EmpName | Salary |
---|---|---|
Engg | Sam | 1000 |
Engg | Smith | 2000 |
Engg | Tom | 2000 |
HR | Denis | 1500 |
HR | Danny | 3000 |
IT | David | 2000 |
IT | John | 3000 |
Notice that Smith and Tom belong to the Engg department and both have the same salary, which is the highest in the Engg department. Hence the query "SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID" will not work since MAX() returns a single value. The below query will work.
SELECT DeptID, EmpName, Salary FROM EmpDetails WHERE (DeptID,Salary) IN (SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID)
Output will be
DeptID | EmpName | Salary |
---|---|---|
Engg | Smith | 2000 |
Engg | Tom | 2000 |
HR | Danny | 3000 |
IT | John | 3000 |
Assuming SQL Server 2005+
WITH cteRowNum AS ( SELECT DeptID, EmpName, Salary, DENSE_RANK() OVER(PARTITION BY DeptID ORDER BY Salary DESC) AS RowNum FROM EmpDetails ) SELECT DeptID, EmpName, Salary FROM cteRowNum WHERE RowNum = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With