简体   繁体   中英

SQL - 2nd highest record in table

SELECT MAX(Score)
FROM Students
WHERE Score < (SELECT MAX(Score) FROM Students);

the above query works perfectly and fetches the record that has 2nd highest score, whereas the query mentioned below does not fetch anything

SELECT *
FROM Students
WHERE Score < (SELECT MAX(Score) FROM Students);

here Students is the table from which I want to fetch all the details of that record which has 2nd highest score in the entire table.

I want that 2nd query should get executed, thanks in advance for helping me out.

  • I have not used any database, I'm simply trying out these queries in w3schools.

With standard SQL, this is typically solved using window functions :

select *
from (
  select *, dense_rank() over (order by score desc) as rnk
  from students
) t
where rnk = 2;

The above is ANSI standard SQL and works on all modern DBMS.

如何使用LIMIT排序并获取返回的第一条记录:

SELECT * FROM Students WHERE Score < (SELECT MAX(Score) FROM Students) ORDER BY Score DESC LIMIT 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM