当前位置:网站首页>The latest entry date of SQL Sever test questions

The latest entry date of SQL Sever test questions

2022-06-24 10:40:00 Cpsu

There is such a line on the buckle SQL Ask for the latest entry date . Here, simply create a table .

CREATE TABLE employees
(name VARCHAR(10) NOT NULL,
in_date date NOT NULL)
--indate Indicates the date of employment 
INSERT INTO employees
VALUES('BOB','2019-11-20'),
	  ('JAM','2020-01-02'),
	  ('MING','2020-02-02'),
	  ('XIA','2020-02-25'),
	  ('AIM','2020-02-25')

When confirming that there is no repetition of the entry date ,mysql It can be used limit function

SELECT name , in_date FROM employees 
 ORDER BY in_date DESC LIMIT 0,1

If there is the same latest entry date , The common way of writing can be as follows

SELECT name , in_date FROM employees 
 WHERE in_date = SELECT MAX(in_date) 
 				 FROM employees

however SQL Sever It doesn't seem to support limit function , Only support top. Then the above question can also be rewritten as ( Again, without repetition )

SELECT TOP 1 * FROM employees ORDER BY in_date DESC	

Of course, subqueries can also be used in general situations , Rewrite into

SELECT * FROM employees 
 WHERE in_date = (SELECT TOP 1 in_date 
 				    FROM employees 
 				   ORDER BY in_date desc)

Here we are expanding , If you want to get the information of the last but three employees ?mysql Very convenient to use limit

SELECT name , in_date FROM employees 
 ORDER BY in_date DESC LIMIT 2,1

but sql I won't support it , therefore sql Implementation may be a little more cumbersome , The first one can be used top, First, take out the information of the last three in reverse order , Reuse top The one who ranks first in the positive order is the last but three night of employment . The expression here may not be clear , You can look directly at the code .

SELECT TOP 1 * 
 FROM  (SELECT TOP 3 * 
          FROM employees 
         ORDER BY in_date DESC) t 
ORDER BY in_date

The second one can use window functions .rank(),dense_rank(),row_number() For the difference between the three rankings, please refer to the article
https://blog.csdn.net/m0_46412065/article/details/104951592

The code is as follows

SELECT name,in_date 
FROM (SELECT name,in_date,
			 DENSE_RANK()OVER(ORDER BY in_date DESC) as req
	    FROM employees) t 
	   WHERE req=3

Finally, I would like to add , The second method is more general , With or without duplicate data , And high expansibility . If you will dense_rank Change it to row_number You can get any row , For example, take the penultimate 8 That's ok , Try it on your own .

原网站

版权声明
本文为[Cpsu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240912595404.html