It is very common question for interview, to find out the 2nd or Nth largest salary of employee.
Please find the below methods to find out the answer :
Method 1 :
SELECT TOP 1 [Column_Name] FROM [Table_Name]
WHERE [Column_Name] NOT IN (SELECT DISTINCT TOP (n-1) [Column_Name] FROM [Table_Name] ORDER BY [Column_Name] DESC )
ORDER BY [Coumn_Name] DESC
Method 2 :
SELECT * FROM (SELECT *, DENSE_RANK() OVER(ORDER BY [Column_Name] DESC ) AS Name FROM [Table_Name]) DQ
WHERE DQ.Name = n
*n = for nth largest
Please find the below methods to find out the answer :
Method 1 :
SELECT TOP 1 [Column_Name] FROM [Table_Name]
WHERE [Column_Name] NOT IN (SELECT DISTINCT TOP (n-1) [Column_Name] FROM [Table_Name] ORDER BY [Column_Name] DESC )
ORDER BY [Coumn_Name] DESC
Method 2 :
SELECT * FROM (SELECT *, DENSE_RANK() OVER(ORDER BY [Column_Name] DESC ) AS Name FROM [Table_Name]) DQ
WHERE DQ.Name = n
*n = for nth largest
No comments:
Post a Comment