使用标准SQL获得第二高的值

时间:2013-06-27 03:20:20

标签: sql

考虑一个名为user的表有两个字段的数据库:

"id" (type: INTEGER, PRIMARY KEY)
"name" (type: VARCHAR(32))

编写标准SQL查询,从id表中检索user的第二高值。返回的值应使用列名id来表示。

哪个是标准SQL?

select id from user order by id desc limit 1,1;

select user.id as id from user order by user.id desc limit 1,1;

如果他们两个都错了,然后正确答案?

5 个答案:

答案 0 :(得分:3)

据我所知,TOPLIMIT都不是由SQL标准定义的(至少我找不到它)。

所以唯一纯粹的标准解决方案是使用窗口函数:

select *
from (
   select id, 
          row_number() over (order by id desc) as rn
   from "user"
) as t 
where rn = 2;

答案 1 :(得分:1)

SELECT MAX( id) FROM user where id !=( SELECT max (id) FROM user ) 

答案 2 :(得分:1)

select 
    secondhighest.id
from 
    "user" highest
    left join "user" biggerthanhighest on 
        biggerthanhighest.id > highest.id
    left join "user" secondhighest on
        highest.id > secondhighest.id
    left join "user"  biggerthansecondhighest on
        biggerthansecondhighest.id > secondhighest.id and
        biggerthansecondhighest.id < highest.id
where
    biggerthanhighest.id is null and
    biggerthansecondhighest.id is null

将避免顶部和子查询。在真正大的桌子上可能会相当快?

答案 3 :(得分:0)

SELECT TOP 1 id
FROM (
SELECT DISTINCT TOP 2 id
FROM user
ORDER BY id DESC) a
ORDER BY id

我认为这是非常标准的。

答案 4 :(得分:0)

SELECT TOP 1 "id" FROM (SELECT TOP 2 "id" FROM "user" ORDER BY "id" DESC) AS "wt" ORDER BY "id"