个人网站
文章首发于小肖学数据分析
描述
有一个员工employees表简况如下:
emp_no | birth_date | first_name | last_name | gender | hire_date |
---|---|---|---|---|---|
10001 | 1953-09-02 | Georgi | Facello | M | 1986-06-26 |
10002 | 1964-06-02 | Bezalel | Simmel | F | 1985-11-21 |
10003 | 1959-12-03 | Parto | Bamford | M | 1986-08-28 |
10004 | 1954-05-01 | Christian | Koblick | M | 1986-12-01 |
请你查找employees里入职员工时间排名倒数第三的员工所有信息,以上例子输出如下:
emp_no | birth_date | first_name | last_name | gender | hire_date |
---|---|---|---|---|---|
10001 | 1953-09-02 | Georgi | Facello | M | 1986-06-26 |
注意:可能会存在同一个日期入职的员工,所以入职员工时间排名倒数第三的员工可能不止一个。
解题思路
(1)、取出入职日期倒数第三的日期
方案一:利用 limit offset 来实现
找到倒数第三个员工的入职日期。通过在子查询中使用LIMIT和OFFSET来实现。LIMIT 1表示我们只关心一个结果,OFFSET 2表示从第三个结果开始。
在主查询中选择所有入职日期等于上一步得到的日期的员工。
方案二:利用rank() over() 开窗函数
使用rank()函数为每个员工分配一个排名,排名从1开始,按入职日期降序排列。筛选出排名为3的员工。
rank()对于排序的数据给予相同序号,接下来的数据序号直接跳跃。
(2)注意点:入职员工时间排名倒数第三的员工可能不止一个
测试数据
drop table if exists `employees` ;
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`));
INSERT INTO employees VALUES(10001,'1953-09-02','Georgi','Facello','M','1986-06-26');
INSERT INTO employees VALUES(10002,'1964-06-02','Bezalel','Simmel','F','1985-11-21');
INSERT INTO employees VALUES(10003,'1959-12-03','Parto','Bamford','M','1986-08-28');
INSERT INTO employees VALUES(10004,'1954-05-01','Chirstian','Koblick','M','1986-12-01');
INSERT INTO employees VALUES(10005,'1955-01-21','Kyoichi','Maliniak','M','1989-09-12');
INSERT INTO employees VALUES(10006,'1953-04-20','Anneke','Preusig','F','1989-06-02');
INSERT INTO employees VALUES(10007,'1957-05-23','Tzvetan','Zielinski','F','1989-02-10');
INSERT INTO employees VALUES(10008,'1958-02-19','Saniya','Kalloufi','M','1994-09-15');
INSERT INTO employees VALUES(10009,'1952-04-19','Sumant','Peac','F','1985-02-18');
INSERT INTO employees VALUES(10010,'1963-06-01','Duangkaew','Piveteau','F','1989-08-24');
INSERT INTO employees VALUES(10011,'1953-11-07','Mary','Sluis','F','1990-01-22');
INSERT INTO employees VALUES(10012,'1955-01-21','zhangsan','Maliniak','M','1989-09-12');
INSERT INTO employees VALUES(10012,'1955-01-21','zhangsan','Maliniak','M','1989-09-12');
SELECT
*
FROM
employees
WHERE
hire_date = ( SELECT hire_date FROM employees ORDER BY hire_date DESC LIMIT 1 OFFSET 2 )
SELECT
emp_no,
birth_date,
first_name,
last_name,
gender,
hire_date
FROM
( SELECT *, rank() over ( ORDER BY hire_date DESC ) rt FROM employees ) a
WHERE
rt =3
SELECT *, rank() over ( ORDER BY hire_date DESC ) rt FROM employees
select *,row_number() over(order by hire_date desc) rt from employees
每日更新:更多资料请关注公众号小肖学数据分析
公众号回复加油即可获取PDF版本