--filter out the max
select max( col )
from [table]
where col < (
select max( col )
from [table] )
--sort top two then bottom one
select top 1 col
from (
select top 2 col
from [table]
order by col) topTwo
order by col desc
在Microsoft SQL中,第一种方法的速度是第二种方法的两倍,即使所讨论的列是集群的。
这是因为与max聚合使用的表或索引扫描相比,排序操作相对较慢。
或者,在Microsoft SQL 2005及以上版本中,你可以使用ROW_NUMBER()函数:
select col
from (
select ROW_NUMBER() over (order by col asc) as 'rowNum', col
from [table] ) withRowNum
where rowNum = 2
select * from (select ROW_NUMBER() over (Order by Col_x desc) as Row, Col_1
from table_1)as table_new tn inner join table_1 t1
on tn.col_1 = t1.col_1
where row = 2
select a.* ,b.* from
(select * from (select ROW_NUMBER() OVER(ORDER BY fc_amount desc) SrNo1, fc_amount as amount1 From entry group by fc_amount) tbl where tbl.SrNo1 = 2) a
,
(select * from (select ROW_NUMBER() OVER(ORDER BY fc_amount asc) SrNo2, fc_amount as amount2 From entry group by fc_amount) tbl where tbl.SrNo2 =2) b
SELECT * FROM `employee` WHERE employee_salary = (SELECT employee_salary
FROM`employee` GROUP BY employee_salary ORDER BY employee_salary DESC LIMIT
1,1)