Q

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.

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

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

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.

0 comments

Oldest 

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:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close