1

I've created a view to query on but does not seem to be working properly. Code:

    CREATE VIEW SpeciesTypes AS
    SELECT species.Name, count(animal.animalID) as number_of_animals
    FROM zoo.species, zoo.animal
    WHERE species.speciesID = animal.speciesID
    GROUP by Name

This code shows each species name and the number of animals within each species. However, i am trying to write a query in finding out which species has the most number of animals including the species name.

The query that i used was:

    SELECT name, max(number_of_animals)
    FROM speciestypes;

This showed me correct highest number of animals but the species name does not change.. does anyone know how to fix this? Thanks!

1 Answer 1

1

If you want to get the name of the species having the greatest number of animals, using your view you can just use a WHERE clause to restrict the result set.

SELECT t.name,
       t.number_of_animals
FROM SpeciesTypes t
WHERE t.number_of_animals = (SELECT MAX(number_of_animals) FROM SpeciesTypes)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer! Yes that works for the final output but my view would require me listing all species and number of animals for each of them, thus i cannot use this method.
@DarioOngsono I updated again. Just query the view and add a WHERE condition to restrict to the species with the max number of animals.
Thank you so much! Works great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.