简体   繁体   English

如何使用sql查询获得第四高的值

[英]How to get the fourth highest value using sql query

I have student table which has column of score.我有学生表,其中包含分数列。 I want to get the fourth highest score,Where the table data is sorted in ascending order.我想获得第四高的分数,其中表数据按升序排列。

这应该有效:

SELECT score FROM table ORDER BY score ASC LIMIT 1 OFFSET 4 

Just add the LIMIT clause:只需添加LIMIT子句:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT 子句可用于限制 SELECT 语句返回的行数。 LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements). LIMIT 接受一个或两个数字参数,它们都必须是非负整数常量(使用准备好的语句时除外)。

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.有两个参数,第一个参数指定要返回的第一行的偏移量,第二个参数指定要返回的最大行数。 The offset of the initial row is 0 (not 1)初始行的偏移量为 0(不是 1)

So you would write:所以你会写:

SELECT column_name
FROM table_name
ORDER BY column_name
LIMIT 3, 1
SELECT score
FROM student
ORDER BY score asc
LIMIT 3, 1

For SQL Server queries one can use folowing statmenet:对于 SQL Server 查询,可以使用以下 statmenet:

with data as 
(
    select
        ROW_NUMBER() OVER (ORDER BY id) as rownum,
        id
    from thetable 
)
select * from data 
where rownum = 4 
order by id asc 

MSSQL doesnt support LIMIT .You have to do it using TOP Keyword or by ROW_NUMBER() for your reference here is the link LIMIT IN MSSQL MSSQL 不支持LIMIT 。您必须使用TOP关键字或通过ROW_NUMBER()来做它供您参考这里是链接LIMIT IN MSSQL

You can do it by using ROW_NUMBER()您可以使用 ROW_NUMBER()

SELECT * FROM (
      SELECT ROW_NUMBER() OVER (ORDER BY score ASC) AS RowNumber,
      *
      FROM student
 ) AS foo
WHERE RowNumber = 4

You will get 4th highest score您将获得第 4 高分

or you can do it like this also或者你也可以这样做

SELECT * FROM (
      SELECT ROW_NUMBER() OVER (ORDER BY score ASC) AS RowNumber,
      *
      FROM student
 ) AS foo
WHERE RowNumber >3 and <=4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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