Solved

SQL Statement - comparing 2 results

Posted on 2013-12-09
5
336 Views
Last Modified: 2013-12-10
Table 1                        Table 2      

AnimalID, COUNT(AnimalID)      AnimalID, Count(AnimalID)

Cat      1                  Cat      4
Dog      4                  Dog       4
Hippo      5            Snake      3
Cow      1                  Frog      4
Frog      2                  Horse      5
                        Sheep      1
                        Pig      3


And I need the resultset to be Table 1 minus Table 2

Cat      -3
Dog      0
Hippo      5
Cow      1
Frog      -2
Snake       -3
Horse      -5
Sheep      -1
Pig      -3

So the first column is an AnimalID, the 2nd is the count of AnimalID.  This information would be the result of Table 1 "SELECT AnimalID, COUNT(AnimalID)FROM Farms WHERE FarmID = 89" and Table 2 "SELECT AnimalID, COUNT(AnimalID)FROM Houses WHERE HouseID = 54"

Any ideas?  I feel like the answer is easy and I should know how to do this but it's not coming to me, help!
0
Comment
Question by:ProdigyOne2k
  • 3
5 Comments
 
LVL 65

Expert Comment

by:Jim Horn
ID: 39707575
Probably a number of ways to pull this off, but the one that immediately comes to mind is...
SELECT AnimalID, SUM(the_count) as total
FROM (
   SELECT AnimalID, COUNT(AnimalID) as the_count
   FROM Table1
   GROUP BY AnimalID
   UNION ALL
   SELECT AnimalID, COUNT(AnimalID) * -1 as the_count
   FROM Table2
   GROUP BY AnimalID) t
GROUP BY AnimalID
ORDER BY AnimalID

Open in new window

0
 
LVL 26

Accepted Solution

by:
Chris Luttrell earned 500 total points
ID: 39707588
Something like this:
SELECT  COALESCE(T1.AnimalId,T2.AnimalId) AS AnimalId,
        COALESCE(T1.Cnt,0) - COALESCE(T2.Cnt,0) Results
FROM
(SELECT AnimalId, COUNT(AnimalId) Cnt FROM Table1 GROUP BY AnimalId) AS T1
FULL OUTER JOIN
(SELECT AnimalId, COUNT(AnimalId) Cnt FROM Table2 GROUP BY AnimalId) T2
ON T2.AnimalId = T1.AnimalId

Open in new window

0
 
LVL 65

Expert Comment

by:Jim Horn
ID: 39707672
ProdigyOne2k - Did you try my solution?  Just curious.
0
 
LVL 65

Expert Comment

by:Jim Horn
ID: 39708479
Actually, the FULL OUTER JOIN looks like the superior solution, as when I ran both and viewed the SET STATISTICS IO ON, the UNION ALL executed in 115ms, and the FULL OUTER JOIN executed in 4ms.

SET SHOWPLAN_XML OFF
GO

IF EXISTS (SELECT name FROM sys.tables WHERE name='animals1') 
	DROP TABLE animals1
GO

IF EXISTS (SELECT name FROM sys.tables WHERE name='animals2') 
	DROP TABLE animals2
GO

CREATE TABLE animals1 (AnimalID varchar(15)) 
CREATE TABLE animals2 (AnimalID varchar(15)) 

INSERT INTO animals1 (AnimalID)
VALUES 
	('Cat'), 
	('Dog'), ('Dog'), ('Dog'), ('Dog'), 
	('Hippo'), ('Hippo'), ('Hippo'), ('Hippo'), ('Hippo'),
	('Cow'), 
	('Frog'), ('Frog')

INSERT INTO animals2 (AnimalID)
VALUES 
	('Cat'), ('Cat'), ('Cat'), ('Cat'), 
	('Dog'), ('Dog'), ('Dog'), ('Dog'), 
	('Snake'), ('Snake'), ('Snake'), 
	('Frog'), ('Frog'), ('Frog'), ('Frog'), 
	('Horse'), ('Horse'), ('Horse'), ('Horse'), ('Horse'),
	('Sheep'), 
	('Pig'), ('Pig'), ('Pig')


SET STATISTICS TIME ON

SELECT 'UNION'
SELECT AnimalID, SUM(the_count) as total
FROM (
   SELECT AnimalID, COUNT(AnimalID) as the_count
   FROM animals1
   GROUP BY AnimalID
   UNION ALL
   SELECT AnimalID, COUNT(AnimalID) * -1 as the_count
   FROM animals2
   GROUP BY AnimalID) t
GROUP BY AnimalID

SELECT 'FULL OUTER JOIN'
SELECT  COALESCE(T1.AnimalId,T2.AnimalId) AS AnimalId,
        COALESCE(T1.Cnt,0) - COALESCE(T2.Cnt,0) Results
FROM
	(SELECT AnimalId, COUNT(AnimalId) Cnt FROM animals1 GROUP BY AnimalId) AS T1
FULL OUTER JOIN
	(SELECT AnimalId, COUNT(AnimalId) Cnt FROM animals2 GROUP BY AnimalId) T2
ON T2.AnimalId = T1.AnimalId
GO

Open in new window

0
 

Author Comment

by:ProdigyOne2k
ID: 39710403
Hey Jimhorn,,
I did not yet but i will check out your last post and let you know how it goes
Thanks!
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Calculate values in an array 18 33
sql server query from excel 3 57
TSQL - IF ELSE? 3 27
Whats wrong in the below query? Any help would be appreciated... 2 14
Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
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…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how the fundamental information of how to create a table.

911 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

16 Experts available now in Live!

Get 1:1 Help Now