Solved

SUM for SQL Query, Grouping and an OTHER column

Posted on 2013-01-22
8
404 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
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 92

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
 
LVL 14

Assisted Solution

by:Christopher Gordon
Christopher Gordon earned 250 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 26

Accepted Solution

by:
Chris Luttrell earned 250 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 69

Expert Comment

by:ScottPletcher
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 26

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 31

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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

762 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now