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

来源:百度知道 编辑:UC知道 时间:2024/05/06 23:45:42
一个Customer表,一个字段Value,现请问如何查到Value中第二大的值?
感觉select max(value) from customer where value <> (select max(value) from customer)不对劲。

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

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

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
得到次大值。

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

最佳的最佳