troubleshooting Question

INVALID SUM RESULTS from SQL JOIN

Avatar of pclarke7
pclarke7 asked on
Oracle DatabaseSQL
22 Comments1 Solution158 ViewsLast Modified:
Hello,
I have two simple tables Header & Detail

Header
Code     Quantity
AAA        10
AAA        20
AAA        30

Detail  
Code     Quantity
AAA       5
AAA       5
AAA       10
AAA       10
AAA       10
AAA       15
AAA       5

I need a SQL statement which will  validate that the Total for Code AAA on the header table  matches the Total for Code AAA on the detail table

  SELECT a.code AS "Code",  SUM(a.quantity ) AS "Header Total", SUM(b.quantity) AS "Detail Total"
  FROM Header a, Detail b WHERE a.code=b.code
  GROUP BY a.code


However I am getting the following for AAA

Code   Header Total          Detail Total
AAA         420                          180


I understand that because it is not a 1 for 1 relationship that this is causing the sum to be aggregated. How can I amend the query to give me the result I require

Code   Header Total          Detail Total
AAA         60                          60
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 22 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 22 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros