2015-07-19 73 views
0

我用下面的表格查找一些數據,找到第二大數字。SQL Server 2008 R2:查找表中第二大數

表:

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

如果最大次數爲兩次在表中? –

+1

@Amit一個簡單的問題並不表示作業/課程。但是,關於自我努力 - 我同意。 –

+1

@RoyiNamir - 那你爲什麼回答這個問題?你不應該鼓勵其他人通過獎勵他們回答這些問題,你應該去激勵他人。 Downvote。 – Amit

回答

2

使用此:

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

感謝馬丁/ dnoeth的評論:

它可與最多2個inetegers

問題

使用此:

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

切換到DENSE_RANK而不是ROW_NUMBER以在多行共享相同工資時獲得正確結果。 – dnoeth

+0

@dnoeth謝謝。事實上,你和馬丁是對的! –

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 
+0

如果出現兩次,這可能會找到最大的數字。 –

+2

或簡單地使用DENSE_RANK而不是ROW_NUMBER – dnoeth

+0

@MartinSmith我開始思考,我的解決方案也會產生錯誤的結果。 –