Skip to content
Advertisement

SQL Combine two queries and SUM

Ok I am a little rusty in SQL. I have 2 exactly same tables with columns ID, Name, Gender, BG. BG is a internal reference. I can query each table individually:

SELECT Gender,BG, COUNT(BG) CountValue
FROM income 
GROUP BY Gender,BG

Result:

   F AA 63 
   F BA 55
   M BB 3

and

SELECT Gender, BG, COUNT(BG) CountValue
FROM outcome
GROUP BY Gender, BG

Result:

   F AA 12 
   F BA 4
   M BB 54

I try to aggregated both using UNION ALL what resulted with a combination of the results bellow. I want to sum them together with the result:

F AA 75 
F BA 59
M BB 57

Advertisement

Answer

Having two identical tables is usually a problem with the data model. You should have one table with another column to indicate “income” or “outcome”.

But, you can use union all and group by:

select gender, bg, sum(cnt)
from ((select gender, bg, count(*) as cnt
       from income
       group by gender, bg
      ) union all
      (select gender, bg, count(*) as cnt
       from outcome
       group by gender, bg
      ) 
     ) io
group by gender, bg;

Using union all ensures that groups that are in only one table are in the result set. Doing the group by first allows each subquery to be optimized, say if there is an index. However, there is overhead for the outer group by as well.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement