牛客sql18 不使用orderby 求薪水第二多员工编号

2020-09-18  本文已影响0人  jiaway

题目sql18

查找当前薪水(to_date='9999-01-01')排名第二多的员工编号emp_no、薪水salary、last_name以及first_name,你可以不使用order by完成吗
CREATE TABLE `employees` (
`emp_no` int(11) NOT NULL,
`birth_date` date NOT NULL,
`first_name` varchar(14) NOT NULL,
`last_name` varchar(16) NOT NULL,
`gender` char(1) NOT NULL,
`hire_date` date NOT NULL,
PRIMARY KEY (`emp_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`));

解答
思路一 先做子查询找到max,然后找到< max的 中的最大值

select e.emp_no,s.salary,e.last_name,e.first_name from employees e,salaries s 
where
e.emp_no = s.emp_no
and
s.to_date='9999-01-01'
and s.salary = ( select max(s1.salary) from salaries s1 
where
s1.salary < ( select max(s2.salary) from salaries s2)) 

思路二 薪水表自相交,然后让左侧薪水 < 右侧薪水,count() 为1 时是第一大,为2 时是第二大,为3 时是第三大

select e.emp_no,s.salary,e.last_name,e.first_name from employees e,salaries s 
where
e.emp_no = s.emp_no
and
s.to_date='9999-01-01'
and s.salary = (
select s2.salary from salaries s1,salaries s2 
where 
s1.salary <= s2.salary group by s1.salary having count(distinct s2.salary)=2
)

上一篇下一篇

猜你喜欢

热点阅读