如何使用 SQL 查询从 table 中查找倒数第二条记录?

How to find second last record from the table using SQL query?

我有学生table,这个table有10条记录。但是我想找出倒数第二条记录,而我只有 table 名称,所以如何找到该记录?

这是我的查询。

select * 
from student 
order by primarykey desc LIMIT 1,1

提前致谢。

应该:

SELECT TOP 1 * FROM
(SELECT Top 2 * FROM student ORDER BY primarykey DESC) x                     
ORDER BY primarykey

你可以这样做:

SELECT * FROM (
                SELECT *,ROW_NUMBER() OVER (PARTITION BY PrimaryKey DESC) AS RN
                ) X
WHERE X.RN=2

子查询将根据 primary key 和 return 以及 row_number() 反转您的结果,从该结果集中您将获取第二行,这将是实际的倒数第二个记录。

使用以下查询:

 select top 1 * from [Your_Table_Name] where [Your_Table_Primary_Name] in
     (select top 3 [Your_Table_Primary_Name] from [Your_Table_Name] order by
      [Your_Table_Primary_Name] desc) 
order by [Your_Table_Primary_Name] asc

描述


1. 首先你需要 select 使用波纹管语法

最后三个记录
 select top 3 [Your_Table_Primary_Name] 
 from [Your_Table_Name] 
 order by [Your_Table_Primary_Name] desc

2. 然后你需要 select 首先使用波纹管语法记录

 select top 1 * 
 from [Your_Table_Name] 
 where [Your_Table_Primary_Name] in (***First Syntax/Above described Syntax*****) 
 order by [Your_Table_Primary_Name] asc

ANSI 标准 SQL 方法是:

select * 
from student 
order by primarykey desc
offset 1 row
fetch first 1 row only;

现在很多(如果不是大多数)数据库都支持它。