Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highest Salary in each department

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.

like image 554
Qinnovator Avatar asked Dec 12 '11 15:12

Qinnovator


People also ask

How can we find highest salary in each department in SQL?

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.

Which department has the highest salary SQL?

For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department.

How do you find the nth highest salary in each 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.


2 Answers

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
like image 163
AVee Avatar answered Sep 21 '22 08:09

AVee


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; 
like image 38
Joe Stefanelli Avatar answered Sep 22 '22 08:09

Joe Stefanelli