简体   繁体   English

SQL 结合两个查询和 SUM

[英]SQL Combine two queries and SUM

Ok I am a little rusty in SQL.好吧,我对 SQL 有点生疏了。 I have 2 exactly same tables with columns ID, Name, Gender, BG.我有 2 个完全相同的表,其中包含 ID、名称、性别、BG 列。 BG is a internal reference. BG 是内部参考。 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.我尝试使用UNION ALL汇总两者,并结合以下结果。 I want to sum them together with the result:我想将它们与结果相加:

F AA 75 
F BA 59
M BB 57

Having two identical tables is usually a problem with the data model.拥有两个相同的表通常是数据 model 的问题。 You should have one table with another column to indicate "income" or "outcome".您应该有一个表和另一列来指示“收入”或“结果”。

But, you can use union all and group by :但是,您可以使用union allgroup 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.使用union all可确保仅在一个表中的组在结果集中。 Doing the group by first allows each subquery to be optimized, say if there is an index.首先进行group by允许优化每个子查询,比如是否有索引。 However, there is overhead for the outer group by as well.但是,外部group by也有开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM