码迷,mamicode.com
首页 > 数据库 > 详细

MySQL_项目7: 各部门工资最高的员工(难度:中等)

时间:2019-04-14 20:42:07      阅读:399      评论:0      收藏:0      [点我收藏+]

标签:char   根据   arc   class   int   str   ane   mys   难度   

项目七: 各部门工资最高的员工(难度:中等)

创建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 |

+----+-------+--------+--------------+

-- 创建employee表
CREATE TABLE employee (
id int(11) NOT NULL,
name varchar(50) NOT NULL,
salary decimal(10,2) NOT NULL DEFAULT 0.00,
departmentid int(11) NOT NULL,
PRIMARY KEY (`id`));

-- 插入数据
INSERT INTO `employee` VALUES (1, Joe, 70000.00, 1);
INSERT INTO `employee` VALUES (2, Herry, 80000.00, 2);
INSERT INTO `employee` VALUES (3, Sam, 60000.00, 2);
INSERT INTO `employee` VALUES (4, Max, 90000.00, 1);
INSERT INTO `employee` VALUES (5, Janet, 69000.00, 1);
INSERT INTO `employee` VALUES (6, Randy, 85000.00, 1);
INSERT INTO `employee` VALUES (7, sherry, 90000.00, 1);
INSERT INTO `employee` VALUES (8, haha, 80000.00, 2);
INSERT INTO `employee` VALUES (9, Abbo, 80800.00, 3);

 

创建Department 表,包含公司所有部门的信息。

+----+----------+

| Id | Name |

+----+----------+

| 1 | IT |

| 2 | Sales |

+----+----------+

-- 创建department表
CREATE TABLE department (
id int(11) NOT NULL,
name varchar(100) NOT NULL,
PRIMARY KEY (`id`));

-- 插入数据
INSERT INTO `department` VALUES (1, IT);
INSERT INTO `department` VALUES (2, Sales);
INSERT INTO `department` VALUES (3, customs);

 

编写一个 SQL 查询,找出每个部门工资最高的员工。例如,根据上述给定的表格,Max 在 IT 部门有最高工资,Henry 在 Sales 部门有最高工资。

+------------+----------+--------+

| Department | Employee | Salary |

+------------+----------+--------+

| IT | Max | 90000 |

| Sales | Henry | 80000 |

+------------+----------+--------+

 

注意点:需要考虑同部门最高工资有多个人的情况

SELECT e.*,t.name department,t.maxsal
FROM employee e
INNER JOIN
                    (SELECT e.departmentid,d.name,MAX(salary) maxsal
                    FROM employee e
                    INNER JOIN department d
                    on e.departmentid = d.id
                    GROUP BY e.departmentid,d.name) t
on e.departmentid = t.departmentid

WHERE e.salary=t.maxsal

 

MySQL_项目7: 各部门工资最高的员工(难度:中等)

标签:char   根据   arc   class   int   str   ane   mys   难度   

原文地址:https://www.cnblogs.com/wodexk/p/10706822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!