SQL Server 2008 R2:查找表中的第二大数字

时间:2015-07-19 10:58:42

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我在下面的表格中找到了第二大数字。

表:

ColA
---------
3
23
43
673
173
373
273

2 个答案:

答案 0 :(得分:2)

使用此:

select * from 
(select colA  , row_number() over(order by colA desc) as rn from Table) T
where T.rn=2

<击>

感谢Martin的/ dnoeth的评论:

2个最大不匹配者可能会出现问题

使用此:

  select * from 
    (select colA  , DENSE_RANK( ) OVER (ORDER BY colA  ) as rn from Table) T
    where T.rn=2

其他信息 :(一劳永逸(学习它!,我总是使用它)):

DECLARE @t TABLE(NAME NVARCHAR(MAX),val money)

insert INTO @t SELECT 'a',100
insert INTO @t SELECT 'a',100
insert INTO @t SELECT 'a',100
insert INTO @t SELECT 'a',100
insert INTO @t SELECT 'b',200
insert INTO @t SELECT 'b',200
insert INTO @t SELECT 'd',400
insert INTO @t SELECT 'e',500
insert INTO @t SELECT 'f',600
select  Name,
        val,
        ROW_NUMBER() OVER (PARTITION BY NAME  ORDER BY name),
        val/ SUM(val) OVER(PARTITION BY NAME )  AS '1AgainstTotalHimself',
        val/ SUM(val) OVER( )  AS '1AgainstOthers' , 
        NTILE(2) OVER ( PARTITION BY NAME ORDER BY name) AS 'ntile2' ,
        NTILE(2) OVER ( ORDER BY name) AS 'ntile' , -- ( 9%2=1  , so group #1 will get more number) 
        RANK( ) OVER ( ORDER BY name  ) AS  Rank,
        DENSE_RANK( ) OVER (ORDER BY name) AS DENSERANK

from @t

结果:

enter image description here

答案 1 :(得分:2)

解决这个问题的一种方法是 <击>

<击>
with cte as (
    select ColA, 
           Row_number() over(order by ColA DESC) As rn
    FROM Table
)

SELECT ColA
FROM cte
WHERE rn = 2

<击>

<强>更新 在马丁的正确评论之后,这是一个更好的答案:

Select top 1 ColA
From YourTable
WHERE ColA < (
   SELECT MAX(ColA) 
   FROM YourTable
)
ORDER BY ColA DESC