【題目描述】
employee
表包含所有員工資訊,每個員工有其對應的 id, salary 和 department id。
+----+-------+--------+--------------+
| id | name | salary | departmentid |
+----+-------+--------+--------------+
| 1 | joe | 70000 | 1 |
| 2 | henry | 80000 | 2 |
| 3 | sam | 60000 | 2 |
| 4 | max | 90000 | 1 |
+----+-------+--------+--------------+
department
表包含公司所有部門的資訊。
+----+----------+
| id | name |
+----+----------+
| 1 | it |
| 2 | sales |
+----+----------+
編寫乙個 sql 查詢,找出每個部門工資最高的員工。例如,根據上述給定的**,max 在 it 部門有最高工資,henry 在 sales 部門有最高工資。
+------------+----------+--------+
| department | employee | salary |
+------------+----------+--------+
| it | max | 90000 |
| sales | henry | 80000 |
+------------+----------+--------+
【題目解答】
首先建表、生成資料
drop table if exists employee;
drop table if exists department;
create table `employee` (
`id` int(11) not null auto_increment,
`name` char(20) not null,
`salary` int(20) not null,
`departmentid` int(11) not null,
primary key(`id`)
)engine=innodb charset=utf8;
create table `department` (
`id` int(11) not null auto_increment,
`name` char(20) not null,
primary key(`id`)
)engine=innodb charset=utf8;
insert into employee(name, salary, departmentid) value("joe", 70000, 1),("8enry", 60000, 2),("sam", 60000, 2),("max", 90000, 1);
insert into department(name) value("it"),("sales");
結果如下
mysql> select d. name as department, e. name as employee, e.salary from departme
nt d, employee e where e.departmentid = d.id and e.salary = ( select max(salary)
from employee where departmentid = d.id );
+------------+----------+--------+
| department | employee | salary |
+------------+----------+--------+
| sales | henry | 80000 |
| it | max | 90000 |
+------------+----------+--------+
2 rows in set (0.00 sec)
力扣資料庫 部門工資最高的員工
部門工資最高的員工 employee 表包含所有員工資訊,每個員工有其對應的 id,salary 和 department id。id name salary departmentid 1joe 7000012 jim9000013 henry 8000024 sam6000025 max90000...
leetcode 求部門工資最高的員工
employee表包含所有員工資訊,每個員工有其對應的 id,salary 和 department id。id name salary departmentid 1 joe 70000 1 2 henry 80000 2 3 sam 60000 2 4 max 90000 1 department...
leetcode 184 部門工資最高的員工
employee 表包含所有員工資訊,每個員工有其對應的 id,salary 和 department id。id name salary departmentid 1 joe 70000 1 2 jim 90000 1 3 henry 80000 2 4 sam 60000 2 5 max 900...