如何在sql server中使用MAX函数查找列的第3个最大值?

时间:2010-03-19 04:32:47

标签: sql-server-2005 select max

昨天我在一次采访中遇到了一个问题,我认为我可以在这里找到答案......

如何在sql server中使用MAX函数找到列的第3个最大值?

将列视为

  

工资
    20000
    15000
10000
45000
50000

9 个答案:

答案 0 :(得分:4)

非常UGLY但只使用MAX

DECLARE @Table TABLE(
        Wages FLOAT
)

INSERT INTO @Table SELECT 20000 
INSERT INTO @Table SELECT 15000 
INSERT INTO @Table SELECT 10000
INSERT INTO @Table SELECT 45000
INSERT INTO @Table SELECT 50000

SELECT  MAX(Wages)
FROM    @Table WHERE Wages < (
                        SELECT  MAX(Wages)
                        FROM    @Table WHERE Wages < (
                                                SELECT  MAX(Wages)
                                                FROM    @Table)
                                )

就个人而言,我会选择

SELECT  *
FROM    (
            SELECT  *,
                    ROW_NUMBER() OVER(ORDER BY Wages DESC) RowID
            FROM    @Table 
        ) sub
WHERE   RowID = 3

然后问面试官为什么他们想要使用MAX的解决方案,他们可以使用内置功能。<​​/ p>

答案 1 :(得分:2)

不使用MAX,这是我能想到的:

SELECT MIN(Wages) FROM
(
    SELECT TOP 3 Wages FROM table ORDER BY Wages DESC;
) As tmp;

通过查找前3名工资来选择表格。然后从上一个结果集中选择min。

UPDATE :好的,只需阅读就必须使用MAX功能。我同意旁观者的回答。

答案 2 :(得分:2)

我们也可以这样做,但我认为这是一个非常糟糕的主意......

SELECT TOP 1 col1 
FROM dbo.temp
WHERE col1 NOT IN ( 
            SELECT TOP 2 MAX(col1) 
            FROM dbo.temp
            GROUP BY col1 
            ORDER BY col1 DESC) 
ORDER BY col1 DESC

答案 3 :(得分:1)

select distinct wages 
from @table e1 
where (select count(distinct sal) from @table e2 where e1.wages <= e2.sal)=3;

答案 4 :(得分:1)

SELECT *

FROM table_name temp1

WHERE (n) = (

SELECT COUNT( DISTINCT (temp2.field_name))

FROM table_name temp2

WHERE temp2.field_name > temp1.field_name

)

这里n = 3,代表第三个最大值

答案 5 :(得分:0)

确定。请阅读我必须使用Max函数:

With RankedWages As
    (
        Select Wage
            , Row_Number() Over( Order By Wage Desc ) As WageRank
        From Wages
    )
Select Wage
From RankedWages As W1
Where WageRank =    (
                    Select Max(W2.WageRank)
                    From RankedWages As W2
                    Where W2.WageRank <= 3
                    )

顺便说一句,如果规则是你 使用MAX(意思是任何地方),那么你可以通过这样做来实现聪明的解决方法:

;With RankedWages As
    (
        Select Wage
            , Row_Number() Over( Order By Wage Desc ) As WageRank
        From Wages
    )
Select Max(Wage)
From RankedWages As W1
Where WageRank = 3

答案 6 :(得分:0)

select MAX(Salary) from ( select top 3 Salary from emp1 order by Salary asc ) as tmp

答案 7 :(得分:0)

select wages from table_name order by wages desc limit 2,1

答案 8 :(得分:-1)

select min(salary) from (select salary from(select salary from table_name order by salary desc)where rownum<=n);

获得第n个最高薪水。

Descrition:

首先按降序排列薪水栏然后选择前3薪水,然后从选择的前3薪水中选择最低薪水,这是第3高薪。