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!


    Requires Free Membership to View

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.

PetTypes 
 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
group
    by case when AnimalType in
                 ( 'Dog', 'Cat' )
            then 'Household Pets'
            when AnimalType in
                 ( 'Snake', 'Tarantula' )
            then 'Exotic Pets'
            else 'Unknown'   
        end       

For More Information


This was first published in April 2004

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.