SQL Exercise 2: Find all information of the third-to-last employee time

SQL Exercise 2: Find all information of the third-to-last employee time

Topic link: Niuke.com

Topic description
Find all the information of the employee who is the third-to-last employee in time. In order to reduce the difficulty of entry, the date of employee entry in all data is not the same day.

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`));

Solution 1
According to the description in the title, the employees’ entry dates are not the same day, then directly hire_datearrange the results in descending order of the columns, and extract one row of data from the third row.

SELECT * FROM employees
ORDER BY hire_date DESC LIMIT 2,1;

Solution 2
Solution 1 has its limitations. When employees’ entry dates are repeated , the results obtained may not be correct. At this time, you can first filter out the date of the third night of entry time, and then find out the employee information whose date is equal to the selected date.

SELECT * FROM employees
WHERE hire_date = (SELECT hire_date 
                   from employees 
                   ORDER BY hire_date DESC LIMIT 2,1)

Guess you like

Origin blog.csdn.net/qq_43965708/article/details/113186501