Highest Salary in each department

前端 未结 30 1456
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 22:16

I have a table EmpDetails:

DeptID      EmpName   Salary
Engg        Sam       1000
Engg        Smith     2000
HR          Denis     1500
HR                  


        
相关标签:
30条回答
  • 2021-01-30 23:13
    with ctesal as (
     select DepartmentId , Name , Salary, ROW_Number() OVER (partition by DepartmentId 
     order by Salary desc) as RowNum
     from dbo.Employee
     )
     select DepartmentId , Name , Salary , RowNum from ctesal where RowNum  =2;
    

    This is applicable to SQL server. ROW_Number is a inbuilt function in SQL server .It gives count starting from 1 based on partition by and order by clause. At the end, We can write where condition based on our requirements.

    0 讨论(0)
  • 2021-01-30 23:15
    select empno 
    from EMP e 
    where salary=(select max(sal) 
                  from EMP w 
                  where  groupby w.deptno having e.deptno=w.deptno)
    

    I hope it will work...

    0 讨论(0)
  • 2021-01-30 23:15
    SELECT D.DeptID, E.EmpName, E.Salary
    FROM Employee E
    INNER JOIN Department D ON D.DeptId = E.DeptId
    WHERE E.Salary IN (SELECT MAX(Salary) FROM Employee);
    
    0 讨论(0)
  • 2021-01-30 23:15

    Use correlated subquery:

    SELECT DeptID, EmpName, Salary
    FROM EmpDetails a
    WHERE Salary = (SELECT MAX(Salary) 
                    FROM EmpDetails b
                    WHERE a.DeptID = b.DeptID)
    
    0 讨论(0)
  • 2021-01-30 23:18

    ermn, something like:

    select 
       d.DeptID,
       max(e.Salary)
    from
       department d
       inner join employees e on d.DeptID = e.DeptID
    group by
      d.DeptID
    
    0 讨论(0)
  • 2021-01-30 23:18

    Here is a way to get maximum values and names on any version of SQL.

    Test Data:

    CREATE TABLE EmpDetails(DeptID VARCHAR(10), EmpName VARCHAR(10), Salary DECIMAL(8,2))
    INSERT INTO EmpDetails VALUES('Engg','Sam',1000)
    INSERT INTO EmpDetails VALUES('Engg','Smith',2000)
    INSERT INTO EmpDetails VALUES('HR','Denis',1500)
    INSERT INTO EmpDetails VALUES('HR','Danny',3000)
    INSERT INTO EmpDetails VALUES('IT','David',2000)
    INSERT INTO EmpDetails VALUES('IT','John',3000)
    

    Example:

    SELECT ed.DeptID
          ,ed.EmpName
          ,ed.Salary
    FROM (SELECT DeptID, MAX(Salary) MaxSal
          FROM EmpDetails
          GROUP BY DeptID)AS empmaxsal
    INNER JOIN EmpDetails ed
      ON empmaxsal.DeptID = ed.DeptID
     AND empmaxsal.MaxSal = ed.Salary
    

    Not the most elegant, but it works.

    0 讨论(0)
提交回复
热议问题