Search code examples
oracle-databasetop-n

Trying to figure out top 5 land areas of the 50 states in the U.S


I have a table created. With one column named states and another column called land area. I am using oracle 11g. I have looked at various questions on here and cannot find a solution. Here is what I have tried so far:

SELECT LandAreas, State 
FROM ( SELECT LandAreas, State, DENSE_RANK() OVER (ORDER BY State DESC) sal_dense_rank
       FROM Map ) 
WHERE sal_dense_rank >= 5;

This does not provide the top 5 land areas as far as number wise.

I have also tried this one but no go either:

SELECT * FROM Map order by State desc) 
where rownum < 5;

Anyone have any suggestions to get me on the right track??

Here is a samle of the table

states      land areas
michagan    15000
florida     25000
tennessee   10000
alabama     80000
new york    150000
california  20000
oregon      5000
texas       6000
utah        3000
nebraska    1000

Desired output from query:

States      land area
new york    150000
alabama     80000
florida     25000
california  20000

Solution

  • Use a HAVING clause and count the number state states larger:

    SELECT m.state, m.landArea
    FROM Map m
    LEFT JOIN Map m2 on m2.landArea > m.landArea
    GROUP BY m.state, m.landArea
    HAVING count(*) < 5
    ORDER BY m.landArea DESC
    

    See SQLFiddle

    This joins each state to every state whose area is greater, then uses a HAVING clause to return only those states where the number of larger states was less than 5.

    Ties are all returned, leading to more than 5 rows in the case of a tie for 5th.

    The left join is needed for the case of the largest state, which has no other larger state to join to.

    The ORDER BY is optional.