Wednesday, June 29, 2016

Simplest SQL Query to find the second largest value?

Simplest SQL Query to find the second largest value?

Answer-1:
SELECT MAX(col)
  FROM table
 WHERE col < (SELECT MAX(col)
                 FROM table)

Answer-2:
SELECT MAX(col) FROM table WHERE col NOT IN (SELECT MAX(col) FROM table);
SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee);


you can find the nth largest value of column by using the following query

SELECT * FROM TableName a WHERE
n = (SELECT count(DISTINCT(b.ColumnName))
FROM TableName b WHERE a.ColumnName <=b.ColumnName);

No comments:

Post a Comment