Solved

SUM for SQL Query, Grouping and an OTHER column

Posted on 2013-01-22
8
409 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
Use Case: Protecting a Hybrid Cloud Infrastructure

Microsoft Azure is rapidly becoming the norm in dynamic IT environments. This document describes the challenges that organizations face when protecting data in a hybrid cloud IT environment and presents a use case to demonstrate how Acronis Backup protects all data.

 
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
 
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: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 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 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: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

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

Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

685 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