Wednesday 19 December 2012

Query to find out the 2nd highest or Nth highest record :

Script to create a table and loading data :

CREATE TABLE test_highest_record
  (
     id     INT IDENTITY(1, 1),
     name   VARCHAR(10),
     salary INT
  )

INSERT INTO test_highest_record
VALUES     ('A',
            10000),
            ('A',
             1000),
            ('B',
             70000),
            ('C',
             40000),
            ('D',
             90000),
            ('E',
             20000),
            ('F',
             300),
            ('G',
             4000),
            ('H',
             11000)

No w check the records in table,

SELECT * 
FROM   test_highest_record 
ORDER  BY 3 

ways to find out the 2nd highest number : 

1). 
SELECT TOP 1 salary 
FROM   (SELECT TOP 2 salary 
        FROM   test_highest_record 
        ORDER  BY 1 DESC) a 
ORDER  BY 1 

2).
SELECT Max(salary) 
FROM   test_highest_record 
WHERE  salary NOT IN (SELECT Max(salary) 
    
                  FROM   test_highest_record) 
3).
SELECT salary 
FROM   (SELECT salary, 
               Row_number() 
                 OVER( 
                   ORDER BY salary DESC) row_id 
        FROM   test_highest_record) a 
WHERE  row_id = 2 

4).
SELECT Max(salary) 
FROM   test_highest_record t1 
WHERE  2 <= (SELECT Count(0) 
             FROM   test_highest_record t2 
             WHERE  t1.salary <= t2.salary) 

To find out the Nth highest Number :

1).
SELECT TOP 1 salary 
FROM   (SELECT TOP @N@ salary 
        FROM   test_highest_record 
        ORDER  BY 1 DESC) a 
ORDER  BY 1 

2).
SELECT salary 
FROM   (SELECT salary, 
               Row_number() 
                 OVER( 
                   ORDER BY salary DESC) row_id 
        FROM   test_highest_record) a 
WHERE  row_id =  @N@

3).
SELECT Max(salary) 
FROM   test_highest_record t1 
WHERE   @N@ <= (SELECT Count(0) 
             FROM   test_highest_record t2 
             WHERE  t1.salary <= t2.salary) 

Note : Replace  @N@ with number .

No comments:

Post a Comment