Nth MAX Salary from Table


Here below is the simplest logic to find nth MAX salary from Salary Table 


DECLARE @Salary TABLE (EmployeeId INT IDENTITY(1,1), Salary INT) /* Temporary Salary Table using Table variable*/
DECLARE @n INT = 3 /* nth MAX Salary, here 3 means 3rd MAX salary */

INSERT INTO @Salary(Salary) VALUES (1000), (2000), (3000), (4000), (2000), (1000), (3000)

Method 1:-

SELECT Salary
FROM   (
           SELECT ROW_NUMBER() OVER(ORDER BY(Salary) DESC) Sno,
                  Salary
           FROM   @Salary
           GROUP BY
                  Salary
       ) a
WHERE  a.Sno = @n

Method 2:-

SELECT TOP 1 Salary FROM (SELECT DISTINCT TOP (@n) Salary FROM @Salary ORDER BY Salary DESC) a
ORDER BY Salary ASC








Comments

Popular posts from this blog

Change Css Class of li in ul onclick

Find missing sequence number. Get the numbers where sequence is missing.

Get Query String Values With Javascript