Ask the Expert

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: