Skip to content
Advertisement

How to write SQL query to get the 2nd heaviest animal from each zoo?

Here are the two tables(animal_weight and zoo_directory):

animal_weights zoo_directory

I am confused on how to retrieve the 2nd heaviest animal from each zoo. I was thinking using the MAX function or a subquery but I am not entirely sure. Here is the query I got so far:

which returns this:

sqlquery

Advertisement

Answer

We can use dense_rank window function to give a rank with weight and per zoo and then filter it out the second highest.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement