SQL查找部门最高薪水

时间:2017-05-31 23:32:35

标签: sql subquery

问题描述:Employee表包含所有员工。每个员工都有一个Id,一个薪水,还有一个部门ID列。

| Id | Name | Salary | DepartmentId |
| 1  | Joe    | 70000  |      1         |
| 2  | Henry | 80000  |      2         |
| 3  | Sam   | 60000  |      2         |
| 4  | Max   | 90000  |      1         |

部门表包含公司的所有部门。

| Id | Name     |
| 1  | IT       |
| 2  | Sales    |

编写SQL查询以查找每个部门中薪水最高的员工。对于上表,Max在IT部门的工资最高,Henry在销售部门的工资最高。

| Department | Employee | Salary |
| IT         | Max      | 90000  |
| Sales      | Henry    | 80000  |

我的问题:我的解决方案如下,但它只能返回最大的工资而不是亨利的工资;但是如果我在子查询中删除“leetdepartment D”,我可以获得2条记录(正确答案)。任何人都可以帮助我理解为什么我应该删除子查询中的“leetdepartment D”?

SELECT D.name, E.name, E.salary 
from leetdepartment D, leetemployee E
where E.deparmentid = D.id
and   salary = (Select MAX(salary) from 
                leetemployee E, leetdepartment D
                where E.departmentid = D.id);

2 个答案:

答案 0 :(得分:0)

private void SyncScrollViewers()
{
    var scrollViewer1 = MyListView1.GetScrollViewer();
    var scrollViewer2 = MyListView2.GetScrollViewer();

    scrollViewer1.ViewChanged += (s, e) =>
    {
        scrollViewer2.ChangeView(null, scrollViewer1.VerticalOffset, null, false);
    };
}

答案 1 :(得分:0)

你可以用以下关系做前1

SELECT top (1) with ties D.name as [Department], E.name as [Employee], E.Salary 
    FROM leetemployee E JOIN leetdepartment D 
on E.deparmentid = D.id
    order by row_number() over (partition by D.name order by E.Salary DESC)