views:

323

answers:

3

Yesterday i had a question in an interview which i thought i could find answers here in SO...

How to find 3rd max value of a column using MAX function in sql server?

Consider the column to be

Wages
20000
15000
10000
45000
50000

A: 

Ok. Read that I must use the Max function:

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
                    )

Btw, if the rule was that you had to use MAX (meaning anywhere), you could have chea..eh..found a clever workaround by doing:

;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
Thomas
@Thomas can i use MAX function?
Pandiya Chendur
How to find 3rd max value of a column using **MAX** function in sql server?
astander
@astander is it possible to use MAX function?
Pandiya Chendur
As a curiosity, was the interview question that you could *only* use MAX or that you *had* to use MAX?
Thomas
I had to use MAX..
Pandiya Chendur
Meaning **only** MAX?
Thomas
@thomas ya.. I wrote your first query but they insisted me to write using MAX
Pandiya Chendur
Gotcha. An intriguing problem with very little use with respect to evaluating a candidate IMO.
Thomas
@Thomas what is IMO?
Pandiya Chendur
@Pandiya Chendur- IMO stands for "In my opinion".
Thomas
+2  A: 

Very UGLY but only using 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)
                                )

Personally I would have gone with

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

And then asked the interviewer why they would ever want a solution using MAX, when they can use built in functionality.

astander
@astander that worked ... But i wrote the 1st query written by thomas in my interview..
Pandiya Chendur
A: 

Without using MAX, this is what I can think:

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

Select the table by finding the top 3 wages. Then select min from the previous result set.

UPDATE: Okay, just read it has to use MAX function. I agree with astander's answer.

SiLent SoNG