[英]How to find second last record from the table using SQL query?
I have student table and there is 10 record in this table. 我有学生表,该表中有10条记录。 But I want to find out the second last record and I have only table name so how can I found that record?
但是我想找出倒数第二个记录,而且我只有表名,那么如何找到该记录呢?
here is my query . 这是我的查询。
select *
from student
order by primarykey desc LIMIT 1,1
Thanks in advance. 提前致谢。
You can do it like this: 您可以这样做:
SELECT * FROM (
SELECT *,ROW_NUMBER() OVER (PARTITION BY PrimaryKey DESC) AS RN
) X
WHERE X.RN=2
The sub query will reverse your result according to primary key
and return the row_number()
along with it, from that result set you are taking the 2nd row which will be the actual 2nd last record. 子查询将根据
primary key
反转您的结果,并返回row_number()
及其结果,您将从该结果集中获取第二行,这将是实际的第二个最后一条记录。
The ANSI standard SQL method is: ANSI标准SQL方法是:
select *
from student
order by primarykey desc
offset 1 row
fetch first 1 row only;
This is now supported in many, if not most, databases. 现在,即使不是大多数数据库,也支持此功能。
Should it : 应该是 :
SELECT TOP 1 * FROM
(SELECT Top 2 * FROM student ORDER BY primarykey DESC) x
ORDER BY primarykey
Use below query: 使用以下查询:
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
Description 描述
1. first you need to select last three records using bellow syntax 1.首先,您需要使用以下语法选择最后三条记录
select top 3 [Your_Table_Primary_Name]
from [Your_Table_Name]
order by [Your_Table_Primary_Name] desc
2. after then you need to select first record using bellow syntax 2.之后,您需要使用以下语法选择第一条记录
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.