[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

SUM for SQL Query, Grouping and an OTHER column

Posted on 2013-01-22
8
Medium Priority
?
414 Views
Last Modified: 2013-01-23
Hello experts:
Suppose this is my data:  "AnimalName" is a column name in my table called "myAnimals" and contains the following values:  

Bird
Cat
Dog
Turtle
Turtle
Bird
Bird
Cat
Dog
Elephant
Cat
Cat
Dog
Bird
Cat
Turtle
Giraffe
Elephant
Dog

Open in new window


I want to count the groups, but lump Giraffes and Elephants into a new group called OTHER.  Also, I want to sum up everything.  The output for the query should look like this:
ALL           19
Bird           4
Cat            5
Dog           4
Turtle        3
Other        3

I can do this:
 SELECT AnimalName, COUNT(*) as "COUNT" from myAnimals where AnimalName in ('Bird','Dog','Cat','Turtle') group by AnimalName  

Open in new window


I can't figure out how to get the OTHER.
Hope this makes sense!  Thanks!
0
Comment
Question by:snix123
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 14

Expert Comment

by:Christopher Gordon
ID: 38807013
Try using a CASE statement

select

      case AnimalName
         when 'Giraffes' then 'Other'
         when 'Elephants' then 'Other'
         else AnimalName
      end as myAnimalName

from myAnimals

group by case AnimalName
         when 'Giraffes' then 'Other'
         when 'Elephants' then 'Other'
         else AnimalName
      end
0
 
LVL 14

Expert Comment

by:Christopher Gordon
ID: 38807023
Oh, I missed the  COUNT(*) as the_Count as an additional field in select.
0
 
LVL 93

Expert Comment

by:Patrick Matthews
ID: 38807050
And to get the 'all':


select 

      case AnimalName
         when 'Giraffes' then 'Other'
         when 'Elephants' then 'Other'
         else AnimalName
      end as myAnimalName,
    COUNT(1) AS Count
from myAnimals

group by case AnimalName
         when 'Giraffes' then 'Other'
         when 'Elephants' then 'Other'
         else AnimalName
      end
union all
SELECT 'ALL' as myAnimalName, COUNT(1) as Count
FROM myAnimals
ORDER BY 2 DESC, 1 ASC

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 14

Assisted Solution

by:Christopher Gordon
Christopher Gordon earned 1000 total points
ID: 38807076
Depending on your version of SQL, you could also use the with rollup keyword in order to get a total at the end of your select like this:

select
      case AnimalName
         when 'Giraffes' then 'Other'
         when 'Elephants' then 'Other'
         else AnimalName
      end as myAnimalName
, count(*) as the_Total

from myAnimals

group by case AnimalName
         when 'Giraffes' then 'Other'
         when 'Elephants' then 'Other'
         else AnimalName
      end with Rollup
0
 
LVL 27

Accepted Solution

by:
Chris Luttrell earned 1000 total points
ID: 38807192
To put it all together and get your row named 'All' with the count at the top try this:
CREATE TABLE #Animal (AnimalName VARCHAR(50));
INSERT INTO #Animal
		( AnimalName )
VALUES	
('Bird'),
('Cat'),
('Dog'),
('Turtle'),
('Turtle'),
('Bird'),
('Bird'),
('Cat'),
('Dog'),
('Elephant'),
('Cat'),
('Cat'),
('Dog'),
('Bird'),
('Cat'),
('Turtle'),
('Giraffe'),
('Elephant'),
('Dog')

SELECT ISNULL(CASE A.AnimalName WHEN 'Elephant' THEN 'Other' WHEN 'Giraffe' THEN 'Other' ELSE A.AnimalName END, 'All') AnimalName, COUNT(*) Count
FROM #Animal A
GROUP BY CASE A.AnimalName WHEN 'Elephant' THEN 'Other'  WHEN 'Giraffe' THEN 'Other' ELSE A.AnimalName END
WITH ROLLUP
ORDER BY AnimalName

DROP TABLE #Animal

Open in new window

results
0
 
LVL 70

Expert Comment

by:Scott Pletcher
ID: 38807900
Careful -- if you add an "Aardvark", the previous code no longer puts "All" first.



CREATE TABLE #Animal (AnimalName VARCHAR(50));
INSERT INTO #Animal ( AnimalName )
VALUES      
('Aardvark'),
('Bird'),
('Cat'),
('Dog'),
('Turtle'),
('Turtle'),
('Bird'),
('Bird'),
('Cat'),
('Dog'),
('Elephant'),
('Cat'),
('Cat'),
('Dog'),
('Bird'),
('Cat'),
('Turtle'),
('Giraffe'),
('Elephant'),
('Dog')

SELECT ISNULL(CASE A.AnimalName WHEN 'Elephant' THEN 'Other' WHEN 'Giraffe' THEN 'Other' ELSE A.AnimalName END, 'All') AnimalName, COUNT(*) Count
FROM #Animal A
GROUP BY CASE A.AnimalName WHEN 'Elephant' THEN 'Other'  WHEN 'Giraffe' THEN 'Other' ELSE A.AnimalName END
WITH ROLLUP
ORDER BY GROUPING ( CASE A.AnimalName WHEN 'Elephant' THEN 'Other'  WHEN 'Giraffe' THEN 'Other' ELSE A.AnimalName END ) DESC, AnimalName

DROP TABLE #Animal
0
 
LVL 27

Expert Comment

by:Chris Luttrell
ID: 38808198
Good catch Scott, we all get caught up with false assumtions with the data we are playing with.

I took it one step further and added a line so it will also sort 'Other' to the end of the list
SELECT ISNULL(CASE A.AnimalName WHEN 'Elephant' THEN 'Other' WHEN 'Giraffe' THEN 'Other' ELSE A.AnimalName END, 'All') AnimalName, COUNT(*) Count
FROM #Animal A
GROUP BY CASE A.AnimalName WHEN 'Elephant' THEN 'Other'  WHEN 'Giraffe' THEN 'Other' ELSE A.AnimalName END
WITH ROLLUP
ORDER BY GROUPING ( CASE A.AnimalName WHEN 'Elephant' THEN 'Other'  WHEN 'Giraffe' THEN 'Other' ELSE A.AnimalName END ) DESC, 
MIN(CASE A.AnimalName WHEN 'Elephant' THEN 2  WHEN 'Giraffe' THEN 2 ELSE 1 END), 
AnimalName

Open in new window

0
 
LVL 32

Expert Comment

by:awking00
ID: 38810235
select 'ALL' as groupname, count(*) cnt from myanimals
union all
select replace(replace(animalname,'Giraffe','Other'),'Elephant','Other'), count(*)
from myanimals group by replace(replace(animalname,'Giraffe','Other'),'Elephant','Other')
;
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
When trying to connect from SSMS v17.x to a SQL Server Integration Services 2016 instance or previous version, you get the error “Connecting to the Integration Services service on the computer failed with the following error: 'The specified service …
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question