1. staff表(.sql文件)
SET FOREIGN_KEY_CHECKS=0;
– Table structure for staff
DROP TABLE IF EXISTS staff
;
CREATE TABLE staff
(
staffId
int(11) NOT NULL,
deptId
int(11) DEFAULT NULL,
staffName
varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
salary
decimal(10,2) DEFAULT NULL,
PRIMARY KEY (staffId
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
– Records of staff
INSERT INTO staff
VALUES (‘1’, ‘1’, ‘丽华’, ‘5000.00’);
INSERT INTO staff
VALUES (‘2’, ‘1’, ‘TOM’, ‘7900.00’);
INSERT INTO staff
VALUES (‘3’, ‘2’, ‘李雷’, ‘3500.00’);
INSERT INTO staff
VALUES (‘4’, ‘2’, ‘韩梅梅’, ‘7900.00’);
INSERT INTO staff
VALUES (‘5’, ‘3’, ‘jerr’, ‘15000.00’);
INSERT INTO staff
VALUES (‘6’, ‘3’, ‘王小二’, ‘5800.00’);
INSERT INTO staff
VALUES (‘7’, ‘1’, ‘李华’, ‘7900.00’);
2.department表(.sql文件)
SET FOREIGN_KEY_CHECKS=0;
– Table structure for department
DROP TABLE IF EXISTS department
;
CREATE TABLE department
(
deptId
int(11) NOT NULL,
areaId
int(11) DEFAULT NULL,
deptName
varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (deptId
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
– Records of department
INSERT INTO department
VALUES (‘1’, ‘1’, ‘产品部’);
INSERT INTO department
VALUES (‘2’, ‘1’, ‘销售部’);
INSERT INTO department
VALUES (‘3’, ‘2’, ‘资金部’);
3.area表(.sql文件)
SET FOREIGN_KEY_CHECKS=0;
– Table structure for area
DROP TABLE IF EXISTS area
;
CREATE TABLE area
(
areaId
int(11) NOT NULL,
areaName
varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (areaId
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
– Records of area
INSERT INTO area
VALUES (‘1’, ‘上海’);
INSERT INTO area
VALUES (‘2’, ‘郑州’);
INSERT INTO area
VALUES (‘3’, ‘杭州’);
查询各部门总工资最高的部门的工资最高的员工姓名,工资,所在区域,部门。
难点:
1.各部门总工资最高的可能有多个部门。
2. 员工工资最高的可能有多人。
select f.staffName as 姓名,f.salary as 工资,ar.areaName as 地区,d.deptName as 部门 from (
select st.deptId,st.staffName,st.salary from (
select c.* from (
select deptId,sum(salary) as sumsal,MAX(salary) as maxsal from staff s
Group by deptid
) c left join (
select deptId,max(sumsal) as maxsum from(
select deptId,sum(salary) as sumsal ,MAX(salary) as maxsal from staff s Group by deptid
) a
) b on c.sumsal=b.maxsum where c.sumsal=b.maxsum
) e left join staff st on st.deptId = e.deptId where st.deptId=e.deptId and st.salary=e.maxsal
)f left join department d on d.deptId=f.deptId
left join area ar on ar.areaId= d.areaId