1.创建一个部门编号,员工编号,员工工资对应表es,再用group by创建一个部门最高工资表ds,用inner join(用where也ok)将两表通过工资和部门编号连接起来,最后再正序排序。
select es.dept_no, es.emp_no, es.salary from
(select d.dept_no, d.emp_no, s.salary from dept_emp as d, salaries as s
where d.emp_no = s.emp_no) as es
inner join
(select d.dept_no, max(s.salary) as maxs from dept_emp as d, salaries as s
where d.emp_no = s.emp_no
group by d.dept_no) as ds
on es.dept_no=ds.dept_no and es.salary=ds.maxs
order by es.dept_no
2.使用窗口函数row_number()给记录进行排序标号,最后限制标号为1。具体操作是row_number() over (partition by 要分组的变量 order by 要排序的变量 desc)。over后面的内容其实相当于group by加order by。要注意的是在where里面不能用别名,因为select是在where之后运行的,where运行的时候还没有变量被赋予别名,所以不能直接在where里用ranking这个昵称,因此需要把整个查询变成子查询,然后在从中把需要的变量提取出来,并用where将ranking限制为1.
select temp.dept_no, temp.emp_no, temp.salary from
(select d.dept_no, d.emp_no, s.salary,
row_number() over (partition by d.dept_no order by s.salary desc) as ranking
from dept_emp as d, salaries as s
where d.emp_no = s.emp_no) as temp
where temp.ranking <= 1