Problem solve Get help with specific problems with your technologies, process and projects.

Grouping by a column that isn't there

Can I get an output like the following from my pet database wherein I would like to group Animal Types into either Household Pets or Exotic Pets and get a total for each group. Column headings for my table are: AnimalID, AnimalName, AnimalType, AnimalDOB, AnimalVisitDate and ClientID. The Output will look like this:

PetType         NumberofAnimals
 Household Pets      50
 Exotic Pets         15

I know the COUNT(*) for aggregates but I could not get 'Household Pets' and 'Exotic Pets' on two rows under a new column heading. Could you please show me? Thanks!

If you had a PetType table, to group your AnimalType values into Pet Types, you would simply join it to the Pets table, and you'd be in business.

 PetType    AnimalType
  Dog        Household Pets
  Cat        Household Pets 
  Snake      Exotic Pets
  Tarantula  Exotic Pets

If you do not have such a table, you can still do the query, but it's messy and difficult to maintain. You'll be constantly revising it as you discover new animal types, instead of just logging them into the PetTypes table, and then, to enter a new pet, just choosing values from a dropdown list.

So here's the messy query:

select case when AnimalType in
                 ( 'Dog', 'Cat' )
            then 'Household Pets'
            when AnimalType in
                 ( 'Snake', 'Tarantula' )
            then 'Exotic Pets'
            else 'Unknown'   
        end     as PetType
     , count(*) as NumberofAnimals
  from Pets
    by case when AnimalType in
                 ( 'Dog', 'Cat' )
            then 'Household Pets'
            when AnimalType in
                 ( 'Snake', 'Tarantula' )
            then 'Exotic Pets'
            else 'Unknown'   

For More Information

Dig Deeper on Oracle and SQL

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.