Solved

SUM for SQL Query, Grouping and an OTHER column

Posted on 2013-01-22
8
410 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 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
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 
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

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

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

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
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
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.

739 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