SQL 12) 获取所有部门中当前员工当前薪水最高的相关信息
获取每个部门中当前员工薪水最高的相关信息
http://www.nowcoder.com/questionTerminal/4a052e3e1df5435880d4353eb18a91c6
方法1)开窗函数 PARTITION BY
SELECT a.dept_no, a.emp_no, a.salary FROM( SELECT de.dept_no,de.emp_no,s.salary, rank() over(PARTITION BY de.dept_no ORDER BY s.salary DESC) rank_n FROM dept_emp AS de JOIN salaries AS s ON de.emp_no=s.emp_no WHERE s.to_date='9999-01-01' AND de.to_date='9999-01-01')a WHERE a.rank_n = 1;
方法2)开窗函数 PARTITION BY
SELECT a.dept_no,a.emp_no,a.salary FROM( SELECT de.dept_no,de.emp_no,s.salary, rank() over(PARTITION BY de.dept_no ORDER BY s.salary DESC) AS rank_num FROM ( SELECT * FROM dept_emp WHERE to_date='9999-01-01') de INNER JOIN( SELECT * FROM salaries WHERE to_date='9999-01-01') s ON de.emp_no=s.emp_no )a WHERE a.rank_num=1;
方法3)子查询
SELECT d1.dept_no, d1.emp_no, s1.salary FROM dept_emp AS d1 INNER JOIN salaries AS s1 ON d1.emp_no=s1.emp_no AND d1.to_date='9999-01-01' AND s1.to_date='9999-01-01' WHERE s1.salary IN (SELECT MAX(s2.salary) FROM dept_emp AS d2 INNER JOIN salaries AS s2 ON d2.emp_no=s2.emp_no AND d2.to_date='9999-01-01' AND s2.to_date='9999-01-01' AND d2.dept_no = d1.dept_no ) ORDER BY d1.dept_no;方法借鉴于网友,但个人感觉存在漏洞
- 假设第二个最高工资表中有5000及10000两个数据,而部门d0002中员工的工资为5000,10000,会同时输出这两个员工的工资