持续更新中
获取所有部门中当前(dept_emp.to_date = ‘9999-01-01’)员工当前(salaries.to_date=‘9999-01-01’)薪水最高的相关信息,给出dept_no, emp_no以及其对应的salary
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,‘d001’,‘1996-08-03’,‘1997-08-03’);
INSERT INTO salaries VALUES(10001,90000,‘1986-06-26’,‘1987-06-26’);
INSERT INTO salaries VALUES(10001,88958,‘2002-06-22’,‘9999-01-01’);
INSERT INTO salaries VALUES(10002,72527,‘1996-08-03’,‘1997-08-03’);
INSERT INTO salaries VALUES(10002,72527,‘2000-08-02’,‘2001-08-02’);
INSERT INTO salaries VALUES(10002,72527,‘2001-08-02’,‘9999-01-01’);
INSERT INTO salaries VALUES(10003,90000,‘1996-08-03’,‘1997-08-03’);
SELECT
d.dept_no,
d.emp_no,
s.salary
FROM
(
SELECT
d.dept_no,
MAX(s.salary) as 'maxsalary'
FROM
dept_emp d JOIN salaries s
ON
d.to_date='9999-01-01' AND s.to_date='9999-01-01' AND d.emp_no=s.emp_no
GROUP BY
d.dept_no
) AS ss,
dept_emp d,salaries s
WHERE
ss.dept_no=d.dept_no
AND
ss.maxsalary=s.salary
AND
d.emp_no=s.emp_no
AND
d.to_date='9999-01-01'
AND
s.to_date='9999-01-01'
ORDER BY
d.dept_no
题目核心:要考虑到薪水最高可能不止一个人,先选出部门-最高薪水表作为筛选条件再进行查询。
salaries
(emp_no
int(11) NOT NULL,salary
int(11) NOT NULL,from_date
date NOT NULL,to_date
date NOT NULL,emp_no
,from_date
));我的第一次答案
SELECT
emp_no,
max(salary)
FROM
salaries
WHERE
to_date='9999-01-01'
AND
salary not in (
SELECT
max(salary)
FROM
salaries
WHERE
to_date='9999-01-01')
未考虑到工资第二高的可能是多个人,这样只选出了第二高工资的编号最前面的员工,之后修改答案如下
SELECT
emp_no,
salary
FROM
salaries
WHERE
to_date='9999-01-01'
AND
salary = (
SELECT
DISTINCT salary
FROM
salaries
WHERE
to_date='9999-01-01'
ORDER BY
salary DESC
LIMIT 1,1)
正确答案,挑选出工资第二高的值再进行筛选
salaries
(emp_no
int(11) NOT NULL,salary
int(11) NOT NULL,from_date
date NOT NULL,to_date
date NOT NULL,emp_no
,from_date
));SELECT
s1.emp_no,
s1.salary,
(SELECT
COUNT(DISTINCT salary)
FROM
salaries
WHERE
to_date='9999-01-01' AND salary>=s1.salary
) AS rank
FROM
salaries s1
WHERE
s1.to_date='9999-01-01'
ORDER BY
s1.salary DESC,s1.emp_no
考点 自身表的复用