在其中一次采访中,有人问我下面的问题
"写一个查询,找出所有部门中薪水最高的所有员工,包括部门名称,员工姓名和工资"
这意味着员工表中有100条记录,部门表中有10条记录。 因此,它需要从查询中提供10条记录,如果任何部门中没有员工,则仍需要显示该部门名称。
由于
答案 0 :(得分:5)
如果没有看到表格结构,我会说你可以用几种不同的方式做到这一点。
使用IN
子句:
select e.name e_name,
d.name d_name,
e.salary
from employee e
inner join department d
on e.deptid = d.id
where e.salary in (select max(salary)
from employee
group by deptid);
或使用子查询:
select e1.name e_name,
d.name d_name,
e1.salary
from employee e1
inner join
(
select max(salary) salary, deptid
from employee
group by deptid
) e2
on e1.salary = e2.salary
and e1.deptid = e2.deptid
inner join department d
on e1.deptid = d.id
参见两者的SQL Fiddle with Demo
现在,MySQL允许您应用聚合函数,而不是将GROUP BY
应用于选择列表中的非聚合字段(这不能在sql server,oracle等中完成)。所以你可以用来获得相同的结果:
select e.name e_name,
d.name d_name,
max(e.salary) salary
from employee e
inner join department d
on e.deptid = d.id
group by d.name
答案 1 :(得分:2)
Table "emp" has
id, name,d_id,salary
and Table "department" has
id, dname
字段。
以下查询将输出部门名称
的最高薪水 SELECT E.id,
E.name,
D.dname,
max(E.salary) as higest_salary
FROM `emp` as E
left join department as D
on D.id=E.d_id
group by E.d_id
答案 2 :(得分:0)
此查询为您提供一个部门列表,其中包含该部门的最高工资(如果存在),否则为null。在这种情况下,选择员工姓名不会为您提供正确的名称,只返回链接部门中的第一个员工!
SELECT
d.name,
MAX(e.salary)
FROM
department d
LEFT OUTER JOIN employee e ON (e.department_id = d.id)
GROUP BY d.id
如果您希望获得薪水和员工姓名最高的部门列表:
SELECT
d.name,
e.name, e.salary
FROM
department d
LEFT OUTER JOIN employee e ON (e.department_id = d.id)
WHERE e.salary IN (
SELECT MAX(em.salary) FROM employee em
WHERE em.department_id = d.id
);
答案 3 :(得分:0)
对于SQL Server 2008 不是最佳解决方案......但是要完全使用从Oracle 10G迁移的HR数据库
select e.DEPARTMENT_ID,d.MaxSalary,es.FIRST_NAME,dm.MinSalary,esd.FIRST_NAME
from EMPLOYEES e
join (select department_id,MAX(salary) MaxSalary from EMPLOYEES group by DEPARTMENT_ID) d
on e.DEPARTMENT_ID=d.DEPARTMENT_ID
join (select first_name,DEPARTMENT_ID from EMPLOYEES ess where SALARY in (select MAX(salary) from EMPLOYEES where DEPARTMENT_ID=ess.DEPARTMENT_ID)) es
on e.DEPARTMENT_ID=es.DEPARTMENT_ID
join (select department_id,min(salary) MinSalary from EMPLOYEES group by DEPARTMENT_ID) dm
on e.DEPARTMENT_ID=dm.DEPARTMENT_ID
join (select first_name,DEPARTMENT_ID from EMPLOYEES ess where SALARY in (select min(salary) from EMPLOYEES where DEPARTMENT_ID=ess.DEPARTMENT_ID )) esd
on e.DEPARTMENT_ID=esd.DEPARTMENT_ID
group by e.DEPARTMENT_ID,d.MaxSalary,es.FIRST_NAME,dm.MinSalary,esd.FIRST_NAME
答案 4 :(得分:-1)
SELECT empname
,MAX(salary
)FROM employee
GROUP BY dep_id
以上查询将生成准确的结果。
答案 5 :(得分:-1)
从emp中选择ename的工资(按部门从emp group中选择max(salary));