题目:有一个员工employees表简况如下:
0BFB4D140D9C3E92AF681D9F9CB92D55 (1)
结果:请你查找employees里入职员工时间排名倒数第三的员工所有信息,以上例子输出如下:
2A26AB183839E3A01C933AE5A75B6D2F
数据表:表结构
代码语言:javascript复制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语句
代码语言:javascript复制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');
解题思路:
- 首先此题是查询入职日期倒数第三的日期。
- 根据日期需要去插入对应,这一天入职的所有员工的信息。
- 此题容易忽略同一天入职日期存在多个,例如2019-06-05存在多个,这时候倒数第三或许就是不真实的倒数第三的日期。因此在查询的时候,需要考虑。可以使用group对日期做一个分组,也可以使用district对日期进行去重,得到的日期就是唯一的。
- 根据得到的日期,作为一个临时表,作为查询所有员工的信息。
参考答案:
- 使用distinct进行排重查询。
select * from employees where hire_date =
(select distinct hire_date from employees order by hire_date limit 2,1);
- 使用group对日期去重查询。
select * from employees where hire_date =
(select hire_date from employees group by hire_date order by hire_date limit 2,1);