描述
有一个员工表dept_emp简况如下:emp_no | dept_no | from_date | to_date |
10001 | d001 | 1986-06-26 | 9999-01-01 |
10002 | d001 | 1996-08-03 | 9999-01-01 |
10003 | d002 | 1996-08-03 | 9999-01-01 |
emp_no | salary | from_date | to_date |
10001 | 88958 | 2002-06-22 | 9999-01-01 |
10002 | 72527 | 2001-08-02 | 9999-01-01 |
10003 | 92527 | 2001-08-02 | 9999-01-01 |
dept_no | emp_no | maxSalary |
d001 | 10001 | 88958 |
d002 | 10003 | 92527 |
示例1
输入:drop table if exists `dept_emp` ; drop table if exists `salaries` ; CREATE TABLE `dept_emp` ( `emp_no` int(11) NOT NULL, `dept_no` char(4) NOT NULL, `from_date` date NOT NULL, `to_date` date NOT NULL, PRIMARY KEY (`emp_no`,`dept_no`)); CREATE TABLE `salaries` ( `emp_no` int(11) NOT NULL, `salary` int(11) NOT NULL, `from_date` date NOT NULL, `to_date` date NOT NULL, PRIMARY KEY (`emp_no`,`from_date`)); INSERT INTO dept_emp VALUES(10001,'d001','1986-06-26','9999-01-01'); INSERT INTO dept_emp VALUES(10002,'d001','1996-08-03','9999-01-01'); INSERT INTO dept_emp VALUES(10003,'d002','1996-08-03','9999-01-01'); INSERT INTO salaries VALUES(10001,88958,'2002-06-22','9999-01-01'); INSERT INTO salaries VALUES(10002,72527,'2001-08-02','9999-01-01'); INSERT INTO salaries VALUES(10003,92527,'2001-08-02','9999-01-01');输出:
d001|10001|88958 d002|10003|92527
题解:
select a.dept_no,a.emp_no,a.salary from (select d.dept_no dept_no,d.emp_no emp_no,s.salary salary from dept_emp d join salaries s on d.emp_no = s.emp_no) a right join (select d.dept_no dept_no,max(s.salary) salary from dept_emp d join salaries s on d.emp_no = s.emp_no group by d.dept_no order by d.dept_no) b on a.dept_no = b.dept_no and a.salary = b.salary;
标签:01,题目,no,薪水,9999,dept,emp,SQL,date From: https://www.cnblogs.com/camping/p/17112776.html