Highest Salary in each department

前端 未结 30 1455
没有蜡笔的小新
没有蜡笔的小新 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:05

    The below listed query will list highest salary in each department.

    select deptname, max(salary) from department, employee where 
      department.deptno=employee.deptno group by deptname;
    

    I executed this query successfully on Oracle database.

    0 讨论(0)
  • 2021-01-30 23:07
    WITH cteRowNum AS (
        SELECT DeptID, EmpName, Salary,
               ROW_NUMBER() OVER(PARTITION BY DeptID ORDER BY Salary DESC) AS RowNum
            FROM EmpDetails
    )
    SELECT DeptID, EmpName, Salary,Rownum
        FROM cteRowNum
        WHERE RowNum in(1,2);
    
    0 讨论(0)
  • 2021-01-30 23:09
    SELECT
        DeptID,
        Salary
    FROM
        EmpDetails
    GROUP BY
        DeptID
    ORDER BY
        Salary desc
    
    0 讨论(0)
  • 2021-01-30 23:09

    The below query will display employee name with their respective department name in which that particular employee name is having highest salary.

    with T as
    (select empname, employee.deptno, salary
    from employee
    where salary in (select max(salary)
    from employee
    group by deptno))
    select empname, deptname, salary
    from T, department
    where T.deptno=department.deptno;
    

    I executed the above query successfully on Oracle database.

    0 讨论(0)
  • 2021-01-30 23:09

    IF you want Department and highest salary, use

    SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID
    

    if you want more columns in employee and department, use

    select  Department.Name , emp.Name, emp.Salary from Employee emp
    inner join (select DeptID, max(salary) [salary] from employee group by DeptID) b
    on emp.DeptID = b.DeptID and b.salary = emp.Salary
    inner join Department on emp.DeptID = Department.id
    order by Department.Name
    

    if use salary in (select max(salary...)) like this, one person have same salary in another department then it will fail.

    0 讨论(0)
  • 2021-01-30 23:10

    If you want to show other parameters too along with DeptId and Salary like EmpName, EmpId

    SELECT 
            EmpID 
          , Name, 
          , Salary
          , DeptId 
       FROM Employee 
       where 
         (DeptId,Salary) 
         in 
         (select DeptId, max(salary) from Employee group by DeptId)
    
    0 讨论(0)
提交回复
热议问题