在其中一次采访中,有人问我以下问题
“写一个查询,找出所有部门的所有员工,该部门的工资最高的部门名称,员工姓名和他的工资”
也就是说,employee 表有 100 条记录,department 表有 10 条记录。所以它需要从查询中给我 10 条记录,加上如果任何部门都没有员工,它仍然需要显示该部门名称。
谢谢
在其中一次采访中,有人问我以下问题
“写一个查询,找出所有部门的所有员工,该部门的工资最高的部门名称,员工姓名和他的工资”
也就是说,employee 表有 100 条记录,department 表有 10 条记录。所以它需要从查询中给我 10 条记录,加上如果任何部门都没有员工,它仍然需要显示该部门名称。
谢谢
在没有看到表结构的情况下,我会说您可能可以通过几种不同的方式来做到这一点。
使用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 允许您应用聚合函数,而不是将 a 应用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
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
此查询为您提供部门列表,如果存在,则具有该部门的最高薪水,否则为 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
);
对于 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
从分组中选择empname
,MAX( salary
)employee
dep_id
以上查询将生成准确的结果。
从emp中选择ename,其中薪水在(按部门从emp组中选择max(salary));