如何一条sql语句查找表中第二大值

2025-02-05 11:28:03
推荐回答(5个)
回答1:

select max(value) from customer 返回的是包括最大值的表 ,是不能与一个值比较的,应该用 in 或 not in操作符,即:
select max(value) from customer where value not in (select max(value) from customer)
在查询中,in 或 not in操作符是索引失效,速度变慢,可以用以下表连接的方法,
select max(value) from (select value from customer) as a left join (select max(value) as c from customer) as b on b.c=a.value where b.c is null
一般来说,以上两种方法的执行速度 表连接的方法好些,但也应该进行测试,我认为,采用两次查询的方法比较合适,select max(value) from customer 得到最大值,
select max(value) from customer where value <6003
得到次大值。

回答2:

select top 1 *
from (select top 2 value from customer order by value DESC) as cust
order by value ASC
先选最大的两个,在从中选择最小的
这样也可以实现

回答3:

用小于号,这样可以排除null
select max(value) from customer where value < (select max(value) from customer)

回答4:

最佳的最佳

回答5:

其时你自己的方法也可以查询了。