Friday, September 6, 2013

To find nth LARGEST value from Table Column


--METHOD 1: TO FIND 2nd LARGEST FROM A TABLE COLUMN
Select max(COLUMN_NAME) from TABLE_NAME where COLUMN_NAME < (Select max(distinct(COLUMN_NAME)) from TABLE_NAME)

--METHOD 2: TO FIND 2nd LARGEST FROM A TABLE COLUMN
Select max(COLUMN_NAME) from TABLE_NAME A where 1 = (Select count(distinct(COLUMN_NAME)) from TABLE_NAME B where B.COLUMN_NAME > A.COLUMN_NAME)

-----------------------------------------------------------------------------------------------
--EXPLANATION METHOD 2: TO FIND nth LARGEST FROM A TABLE COLUMN
/*
Select max(COLUMN_NAME) from TABLE_NAME A where N-1 = (Select count(distinct(COLUMN_NAME)) from TABLE_NAME B where B.COLUMN_NAME > A.COLUMN_NAME)
*/
--THEREFORE, e.g. TO FIND 45th LARGEST, QUERY WILL BE
Select max(COLUMN_NAME) from TABLE_NAME A where 44 = (Select count(distinct(COLUMN_NAME)) from TABLE_NAME B where B.COLUMN_NAME > A.COLUMN_NAME)

No comments: